在div内部水平居中元素

时间:2013-04-14 23:31:02

标签: html5 css3 html alignment

为了简单起见,假设你有一个100px宽的div,并且每个20px宽的内部有3个div。如何将它们对准到div的中心位置,留下20px;双方的差距?

2 个答案:

答案 0 :(得分:3)

中心一些HTML元素总是取决于您的项目和集成依赖...

您可能对这两种解决方案感到满意,显示:inline-block;和float:left;

两者都有优点和缺点缺点,希望它可以帮助你!

http://jsfiddle.net/HP2DS/1/

<!-- Inline-block -->
<div id='container'>
    <div class='centered' id='content-left'></div><div class='centered' id='content-center'></div><div class='centered' id='content-right'></div>
</div>

#container {
    width: 100px;
    height: 80px;
    text-align: center;
    background: cyan;
}

#container .centered {
    display: inline-block;
    width: 20px;
    height: 100%;
    margin: auto;
    background: magenta;
    border: 1px solid black;
    box-sizing: border-box;
}

<!-- Floating -->
<div id='container-2'>
    <div class='centered' id='content-2-left'></div>
    <div class='centered' id='content-2-center'></div>
    <div class='centered' id='content-2-right'></div>
</div>

#container-2 {
    width: 60px; /* 60px + 2*20px of padding... */
    height: 80px;
    padding: 0 20px;
    text-align: center;
    background: cyan;
}

#container-2 .centered {
    float: left;
    width: 20px;
    height: 100%;
    margin: auto;
    background: magenta;
    border: 1px solid black;
    box-sizing: border-box;
}

答案 1 :(得分:1)

美好的一天!以下是我实施它的方法:

<强> HTML

<div id="container">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>

<强> CSS

#container {
  width: 100px;
  height: 100px;
  border: 1px solid red; /** for viewing purposes **/
  text-align: center; /** center the divs **/
  font-size: 0; /** remove the unwanted space caused by display: inline-block in .child **/
}

#container .child {
  display: inline-block; /** set the divs side-by-side **/
  vertical-align: top;
  width: 20px;
  height: 100px;
  font-size: 12px; /** override font-size: 0 of #container, so that text will be visible again **/
  text-align: left; /** set text in the .child divs back to normal alignment **/
  border: 1px solid blue; /** for viewing purposes **/
  box-sizing: border-box;
}

我希望这会有所帮助。干杯! :)