3

I've used a ul in a paragraph tag and used CSS to hide it, but it won't work. How can I fix it?

Here's my HTML content:

<p id="transport">
    <img class="draco" src="../image/draco.png"/>
    <ul>
        <li><a href="">a</a></li>
        <li><a href="">b</a></li>
        <li><a href="">c</a></li>
        <li><a href="">d</a></li>
        <li><a href=""></a></li>
    </ul>
</p>

And here is my CSS content:

p#transport ul {
    background-color: rgba(0,0,0,1.0);
    position: absolute;
    float: right;
    display: none;
}

p#transport:hover ul {
    display: block;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
I I
  • 51
  • 1
  • 6
  • 3
    This is because you can't have an `ul` inside a `p` tag. The browser will adjust it for you. – putvande Aug 17 '14 at 09:07
  • i've change it to div and it works! THKS! – I I Aug 17 '14 at 09:09
  • It should. Look at http://jsfiddle.net/6a0awqgv/embedded/result/ and check in your console where the HTML ends up. The browser will place the `ul` outside the `p`. – putvande Aug 17 '14 at 09:10
  • [The short answer is that ul elements are not legally allowed inside `p' elements.](http://stackoverflow.com/questions/5681481/should-ol-ul-be-inside-p-or-outside#answer-5681796) – Deepak Ingole Aug 17 '14 at 09:11

2 Answers2

4

This is because you can't have an ul inside a p tag. Most browsers will change the HTML for you: place the ul outside the p tag. This is what it well may end up looking like:

<p id="transport">
    <img class="draco" src="../image/draco.png">
</p>
<ul>
    <li><a href="">a</a></li>
    <li><a href="">b</a></li>
    <li><a href="">c</a></li>
    <li><a href="">d</a></li>
    <li><a href=""></a></li>
</ul>
<p></p>

Check http://jsfiddle.net/6a0awqgv/embedded/result/. Compare the source code with the element inspector in your console.

So to overcome it you could do:

p#transport + ul {
    background-color: rgba(0,0,0,1.0);
    position: absolute;
    float: right;
    display: none;
}

p#transport:hover + ul{
    display: block;
}

The + is the adjacent selector

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
putvande
  • 15,068
  • 3
  • 34
  • 50
4

That is because you cannot put a ul inside a p. The browser interprets it as if you have forgotten to close the p tag and closes it itself. That is the reason the CSS rules do not apply.

Change the p tag to a div and it'll work just fine.

praty
  • 914
  • 9
  • 11