li float vs display: inline

穿精又带淫゛_ 提交于 2019-12-03 09:36:47

问题


Is there a best choice out of float: left or display: inline for aligning list items horizontally?

eg: http://www.vanseodesign.com/css/simple-navigation-bar-with-css-and-xhtml/

Personally I dislike float, but that maybe more of an emotional thing rather than logical.


回答1:


ul { list-style-type: none; overflow: hidden; width:200px; }
ul li { float:left; width: 100px; }
ul li a { display: block; padding: 10px; width:80px; }
ul li a:hover { background: black; }


<ul>
  <li><a href="http://www.facebook.com">Facebook</a></li>
  <li><a href="httpt://www.google.com">Google</a></li>
</ul>

This is what I prefer mostly because when you use display:inline you cannot set properties like width, padding (top and bottom), margin etc... which is an handicap for layout purposes.

EDIT 2014

It is also an option to use the display: inline-block property. One think to note is that once you make the list elements inline or inline-block, white-spaces will be taken into consideration. Hence, there will be unwanted spaces between elements.

ul { list-style-type: none; width: 300px; font-size: 0; }
ul li { display: inline-block; *display: inline; zoom: 1; margin-right: 10px; } 
/* The *display and zoom is a IE hack, though can't remember 
   now which one (guess it is IE7) */
ul li a { display: inline-block; padding: 10px; font-size: 13px; }

Check the fiddle here.

If you don't want to use the font-size property (for browser compatibility issues), you can also use html comments to get rid off whitespaces! Though I prefer the method above.

   <ul><!--
    --><li><a href="http://www.facebook.com">Facebook</a></li><!--
    --><li><a href="httpt://www.google.com">Google</a></li><!--
--></ul>



回答2:


What about

li {
       display:inline-block
};

You can then set properties like width, heigth, padding, margin, etc..




回答3:


I have noticed some rendering bugs when displaying LI's Inline in chrome. My LI border sometimes does not render with the proper horizontal padding.

In general though, I like Inline, it still gives you horizontal margining and padding and you can do a nice text-align: center; on the UL and use the UL for vertical spacing.

I tend to use float purely because an LI is a block element by default and should be treated that way in my opinion but there are clear use cases for both.




回答4:


It's personal preference.

From a CSS point, Display:Inline = Float:Left(Right).
When it comes to making elements horizontal, like <li>.

The css rule Float is newer than Display.



来源:https://stackoverflow.com/questions/8970650/li-float-vs-display-inline

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!