I          I
I I

Reputation: 51

Why can't I hide my 'ul' with CSS like this?

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;
}

Upvotes: 3

Views: 3056

Answers (2)

putvande
putvande

Reputation: 15213

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

Upvotes: 4

praty
praty

Reputation: 1121

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.

Upvotes: 4

Related Questions