Which is better for left-to-right layout: float or display:inline?

给你一囗甜甜゛ 提交于 2019-12-22 16:32:13

问题


I have some icons inside divs and needed to lay them out with a left-to-right structure instead of the default top-to-bottom layout that seems to come with divs. It's probably not news to most people who know CSS but I figured out (with a little help) that I could cause the divs to layout left-to-right using either:

float: left/right 

or

display:inline. 

My question is - is one preferable over the other?

<div id="icons">

  <div id="divtxt" class="divicon">
    <img src="/icons/text.png" id="icontxt" class="icon"/>
  </div>

  <div id="divpdf" class="divicon">
    <img src="/icons/pdf.png" id="icondoc" class="icon"/>
  </div>

  <div id="divrtf" class="divicon">
    <img src="/icons/rtf.png" id="iconrtf" class="icon"/>
  </div>
</div>

  div#icons
  {
    width:200px;
    height: 100px;
  }

  div.divicon
  {
    margin: 0 0 0 0;
    padding: 0 0 0 0;
    border: 0 0 0 0;
  }

回答1:


You cannot set an explicit width/height on inline elements, so if they must be a specific size then you're stuck with floating them. Floating elements can cause various layout quirks, so inline is definitely preferred if you don't have to float things.

Here, you should be able to set the size on the images instead of the divs. Then you could change the divs to spans which would naturally expand to the size of the images inside. (A span is just the inline companion to div, no need to create divs and then force them to display: inline.)




回答2:


One is not preferable over the other; they do different things. When something is displayed inline, content that overflows the current line wraps to the next line. A float, on the other hand, keeps the div displayed in a rectangular block. So depending on your specific situation, you may find both useful.

In your given example, float would probably work much better.



来源:https://stackoverflow.com/questions/1107820/which-is-better-for-left-to-right-layout-float-or-displayinline

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