Horizontally align div without float [duplicate]

痴心易碎 提交于 2020-01-10 22:04:42

问题


I want to know if there exists an elegant way to horizontally align 3 divs without using float css property.

HTML:

<div id="parent">  
  <div id="first">Left</div>  
  <div id="second">Middle</div>  
  <div id="third">Right</div>
</div>

I ask this question because the parent div has not float property and adding float to children cause problems on page resizing.


回答1:


You can use display:inline-block or display:table-cell with the inner content.

  • Flex layout (See also T J's answer):
#parent{ display:flex; justify-content: space-between; }

JSFiddle

  • Table layout:
#parent{ display:table; width:100%; }
#parent div{ display:table-cell; }
#first{ text-align:left; }
#second{ text-align:center; }
#third{ text-align:right; }

JSFiddle

  • Inline-block layout :
#parent{ width:100%; white-space:nowrap; }
#parent div{ display:inline-block; width:33.3%;}
#first{ text-align:left; }
#second{ text-align:center; }
#third{ text-align:right; }

JSFiddle




回答2:


Adding to notulysses's answer, If ancient browser support is not an issue, you can use css3 Flexible_boxes.

By applying display:flex the child divs will be aligned horizontally (by default)

#parent{
 display:flex;
 justify-content:space-around;
}

more about flexbox @ CSSTricks

This will avoid the white space issue with inline-block elements

JSfiddle




回答3:


Instead of finding a workaround for floating, you could also use the following fix for your "resizing problems" (at least what I think it is caused by):

After using floats, you should always clear your floats. You can do this by adding an extra <div> with a class.

<div id="parent">  
  <div id="first">Left</div>  
  <div id="second">Middle</div>  
  <div id="third">Right</div>
  <div class="clear"></div>
</div>

In CSS:

.clear{
  clear: both;
}



回答4:


#parent { 
    display: table; 
}

#first, #second, #third { 
    display: table-cell; 
}



回答5:


Use the CSS style below :

#parent div{ display: inline-block; }

Working Fiddle




回答6:


With the CSS below you can achieve your goal :

#parent{
 width:140px;
    height:30px;
    border:1px solid #CCC; 
}
#first{
    width:19px;
    height : inherit;
    display:inline;
    border : 1px solid red;
}
#second{
    width:19px;
    height : inherit;
    display:inline;
    border : 1px solid green;
}
#third{
    width:19px;
    height : inherit;
    display:inline;
    border : 1px solid blue;
}

Fiddle



来源:https://stackoverflow.com/questions/24261376/horizontally-align-div-without-float

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