CSS - 如何并排放置div,左右没有空格

时间:2014-10-25 10:45:17

标签: html css html5 css3

我有一个父div与多个子div,我想让子div并排浮动4行。

浮动规则必须:

  1. 每个孩子都有相同的宽度。
  2. 每行4个孩子。
  3. 每行左侧和右侧必须用包装器关闭(0px /无空格),如下图所示。
  4. 每个子div之间的每一行必须有一个空格,且大小必须相同,如下图所示。
  5. enter image description here

    通过使用css / css3可以做到吗?对不起我的英语不好。

6 个答案:

答案 0 :(得分:2)

使用CSS3这相对容易:使用box-sizing: border-box;,子div的宽度将包括填充(例如20px)和边框,并且可以设置为正文宽度的25% 。给父div,包装器,负右边距以隐藏最右边的空间。由于这个额外的空间,身体上会出现一个滚动条,可以用overflow-x: hidden;隐藏。



body {
  margin: 0;
  padding: 0;
  overflow-x: hidden;
}
.wrapper {
  margin-right: -20px;
}
.child {
  box-sizing: border-box;
  width: 25%;
  padding-right: 20px;
  float: left;
}
.child p {
  background: lime;   
}

<p>Content</p>
<div class="wrapper">
  <div class="child"><p>Child</p></div>
  <div class="child"><p>Child</p></div>
  <div class="child"><p>Child</p></div>
  <div class="child"><p>Child</p></div>
</div>
<p>Content</p>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

这里有一些非常好的例子,但是我总是想看看让我的图像与文字对齐的方法。要做到这一点,我一直在使用页面包装器和带有负边距的图像包装器(使其与文本不一致)。然后,将相同的值应用为正填充值后,图像与文本完全对齐。

#pagewrapper {
    width: 500px;
    background: green;
    overflow: hidden;
}

#imagewrapper {
    width: auto;
    margin: 0 -12px; /* negative margin to keep images aligned with text, same as margin below */
    background: blue;
}

.image {
    box-sizing: border-box;
    width: 25%;
    padding: 0 12px;
    margin: 0;
    height: 200px;
    background: red;
    float: left;
    overflow: hidden;
}

Fiddle

答案 2 :(得分:0)

刚看到,@ user2782378回答..我想我应该通过给出答案来详细说明:

div{float:left;width:20%;background:black;height:100px;margin:1px;}

Js fiddle EXAMPLE

用于研究使用的CSS:

W3schools

答案 3 :(得分:0)

尝试按比例使用display:inline-block修改子div的宽度

.outer_div{
  display:inline-block;
  max-width:800px;
  height:300px;
  background-color:red;
  overflow:auto;
}
.inner_div{
  width:200px;
  height:100px;
  background-color:black;
  float:left;
}

答案 4 :(得分:0)

也许这种纯CSS2解决方案更可取。

div是一个块元素,默认为页面的宽度。如果给包装器div一个右边距是内部div之间边距的三倍,则包装器宽度的25%正好是内部div的宽度。通过相对定位调整内部div的位置:

html, body {
    margin: 0;
    padding: 0;
}
.wrapper {
    margin-right: 30px;
}
.wrapper div {
    width: 25%;
    float: left;
    position: relative;
    background: lime; /* demo setting */
    height: 100px;    /* demo setting */
}
.wrapper div+div {
    left: 10px;
}
.wrapper div+div+div {
    left: 20px;
}
.wrapper div+div+div+div {
    left: 30px;
}
<div class="wrapper">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>

答案 5 :(得分:-1)

试试这个..

.row {
  width: 100%;
  text-align: center; // center the content of the container
}

.block {
  width: 100px;
  display: inline-block; // display inline with abality to provide width/height
}​
  • 有保证金:0自动;除了宽度:100%是没用的,因为你的元素将占用整个空间。

  • float:left将浮动左边的元素,直到没有剩余空间,因此它们将继续新的行。使用display:inline-block能够显示内联元素,burt能够提供大小(与显示内联的宽度/高度被忽略的比较)

Demo

相关问题