css:50%宽度div之间的20px gutter

时间:2013-09-08 14:18:59

标签: html css css-float

我有一个宽度为100%的容器div,里面有2个.block div,宽度均为50%,显示内联块并向左浮动。是否可以在这些div之间保持一致的20px排水沟? 我尝试了一种简单的方法,将它们的宽度设置为49%,并在左侧设置2%的右边距,但理想情况下,如果可能的话,我希望在这两个div之间保持一致的20px排水沟。
jsFiddle demo :http://jsfiddle.net/D6U3t/

HTML:

<div class="container">
    <div class="block"></div>
    <div class="block"></div>
</div>

CSS:

.container {
    position: absolute;
    top: 0; left: 0;
    width: 100%; height: 300px;
    background-color: silver;
}

.block {
    position: relative;
    width: 50%; height: 200px;
    background-color: red;
    display: inline-block;
    float: left;
}

任何建议都将不胜感激!

5 个答案:

答案 0 :(得分:3)

如果包装div可以接受,我可以帮到你。 * {box-sizing: border-box;}中的秘密(通常是)。

Fiddle

答案 1 :(得分:0)

你必须再增加一节课。我认为它的工作。

    .block:last-child {
     margin-left:20px;
     float:right;
     }

&安培;将.block宽度减少到49%。

查看fiddile:http://jsfiddle.net/D6U3t/14/

由于

答案 2 :(得分:0)

我会在父容器上使用填充,然后让子容器为100%宽度和100%高度。

查看我的JSFiddle:http://jsfiddle.net/D6U3t/10/

HTML

<div class="container">
    <div class="block first">
        <div class="inner-block"></div>
    </div>
    <div class="block second">
        <div class="inner-block"></div>
    </div>
</div>

CSS

* {
    box-sizing: border-box;
}

.container {
    margin: 0;
    width: 100%; 
    height: 100%;
    background-color: silver;
}

.block {
    position: relative;
    width: 50%; 
    height: 200px;
    float: left;
}

.block.first {
    padding: 0 10px 0 0;
}

.block.second {
    padding: 0 0 0 10px;
}

.inner-block {
    height: 100%;
    width: 100%;
    background-color: red;
}

答案 3 :(得分:0)

我使用内部容器来解决问题。

fiddle: http://jsfiddle.net/kpwp7/4/

答案 4 :(得分:0)

如果您的browser support要求允许,您可以使用calc() CSS功能:

http://codepen.io/troywarr/pen/MaVKGe?editors=110

<强> HTML:

<div class="container">
    <div class="block"></div>
    <div class="block"></div>
</div>

<强> CSS:

.container {
    position: absolute;
    top: 0; 
    left: 0;
    width: 100%; 
    height: 300px;
    background-color: silver;
}

.block {
    width: calc(50% - 10px); /* subtract half of 20px gutter */
    height: 200px;
    background-color: red;
}

.block:first-child {
  float: left;
  margin-right: 10px; /* half of 20px gutter */
}

.block:last-child {
  float: right;
  margin-left: 10px; /* half of 20px gutter */
}
相关问题