开发者

Why is this :after element being affected by line breaks?

开发者 https://www.devze.com 2023-03-19 11:09 出处:网络
I have a simple menu coded up like this <ul id=\"main-menu\" class=\"container\"> <li><a href=\"#\">About Us</a></li>

I have a simple menu coded up like this

<ul id="main-menu" class="container">
    <li><a href="#">About Us</a></li>
    <li><a href="#">Home</a></li>
    <li><a href="#">Villas & Yachts</a></li>
    <li><a href="#">Islands</a></li>
    <li><a href="#">Gallery</a></li>
    <li><a href="#">Blog</a></li>
    <li><a href="#">Get In Touch</a></li>       
 </ul>

which looks like this

Why is this :after element being affected by line breaks?

The little dots in-between each menu item are created using the :after pseudo element. Eveything is working fine, but I also need sub menus, which will be nested lists.

The problem is, when i add a line break to the menu like this

<ul id="main-menu" class="co开发者_如何学Cntainer">
    <li><a href="#">About Us</a></li>
    <li><a href="#">Home</a></li>
    <li><a href="#">Villas & Yachts</a>
    <!-- LINE BREAK -->
    </li>
    <li><a href="#">Islands</a>
    <!-- LINE BREAK -->
    </li>
    <li><a href="#">Gallery</a></li>
    <li><a href="#">Blog</a></li>
    <li><a href="#">Get In Touch</a></li>       
 </ul>

I get this result in Safari & Chrome (But not Firefox)...

Why is this :after element being affected by line breaks?

It seems to me as though webkit is treating the whitespace as 'pre'. The CSS for the :after element looks like this

ul#main-menu li:after
{
    content: "\00b7";
    width: 61px;
    float: right;
    text-align: center;
    border: rgba(225,225,225,0.25) 1px solid;
}

I've also tried setting white-space: normal/nowrap on the ul, li and :after elements which doesn't affect anything.

Can anyone see where I'm going wrong, or is this a problem with Webkit/Firefox?

UPDATE

I've created a demo at http://jsfiddle.net/zmVbH/


The issue is that the line break is white space which makes the floated content drop a line. The issue can be reproduced by adding a single space between the </a> and </li>. Try making the inserted content display:inline-block instead of floated.

ul#main-menu li:after
{
    content: "\00b7";
    width: 61px;
    display:inline-block;
    text-align: center;
    border: rgba(0,0,0,0.25) 1px solid;
    white-space: normal;        
}

Updated JSFiddle.

UPDATE BY OP

Yup, inline-block fixes this, but it's not quite that simple since inline-block has some patchy browser support.

ul#main-menu li:after
{
    content: "\00b7";
    width: 61px;
    float: right;
    text-align: center;
    border: rgba(225,225,225,0.25) 1px solid;

    /* FIX */
    display:-moz-inline-stack; /* For older versions of Firefox */ 
    display:inline-block; /* Anything that supports inline-block */

    /* IE FIX */
    zoom:1;
    *display:inline; 
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号