如何精确调整子div到父div

时间:2015-12-30 20:21:51

标签: html css

我有一个父亲div,它拥有3个div子,我尝试将3个div调整为父亲宽度但是我在第三个div之后有一点间隙,我该如何解决呢?

HTML

 <div id="main">
      <div id="first" style="width:100%;float:left">
           <div>1</div>
           <div>2</div>
           <div>3</div>
      </div>
 </div>

CSS

div {
    border: 1px;
    border-style: double;
}

div#first> div{
    width:33%;
    float:left;
    display:block;
}

3 个答案:

答案 0 :(得分:2)

您可以使用flexbox非常简单地实现此布局。

<强> HTML

<div id="main">
    <div id="first">
        <div>1</div>
        <div>2</div>
        <div>3</div>
    </div>
</div>

<强> CSS

div#first { display: flex; }
div#first > div { flex: 1; }

DEMO

flexbox的好处:

  1. 最小代码;效率很高
  2. centering, both vertically and horizontally, is simple and easy
  3. equal height columns are simple and easy
  4. multiple options for aligning flex elements
  5. 响应
  6. 与花车和桌子不同,浮动和桌面提供有限的布局容量,因为它们从未用于建筑布局,因此flexbox是一种现代(CSS3)技术,具有广泛的选项。
  7. 要了解有关flexbox的更多信息,请访问:

    请注意,所有主流浏览器except IE 8 & 9都支持flexbox。最近的一些浏览器版本,例如Safari 8和IE10,需要vendor prefixes。要快速添加所需的所有前缀,请在左侧面板中发布CSS:Autoprefixer

答案 1 :(得分:1)

&#13;
&#13;
div {
  border: 1px;
  box-sizing: border-box; /* which give padding and border from inside */
  border-style: double;
}

/* i have used below code to clear the floats 
   or you can also use <div class="clear"></div> to clear the floats
*/

#first:after,
#first:before {
  content: '';
  display: table;
  clear: both;
}

div#first > div {
  width: 33.33%; /* changed the width from 33% to 33.33% */
  background: red;
  float: left;
  display: block;
}
&#13;
<div id="main">
  <div id="first"> <!-- no need to add because i have cleared the floats and also by default div is a block element it will take 100% -->
    <div>1</div>
    <div>2</div>
    <div>3</div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

div:last-child{
   margin:0px !important;
   padding: 0px !important;
}

因为你有一个边框,你可能需要减少32%的宽度来容纳像素。