0

你如何使用带有百分比和边距的边框?示例如下。

<style>
.half{
    width: 50%;
    float: left;
    background: red;
    margin: 5px;
    box-sizing: border-box;
            box-shadow: 0px 0px 3px black;
}
</style>
<div class="half">half</div>
<div class="half">half</div>

我希望 div(.half) 占据屏幕的 50% - 每次尝试时,div 周围的 5px 边距都是可行的,它使其宽度超过 50%,并将第二个框放在我想要的下一行如果可能的话,避免基于百分比的边距。

4

3 回答 3

3

边距永远不会作为宽度的一部分计算,即使使用 box-sizing: border-box;

所以尝试用border: 5px solid transparent


或者,如果您不能覆盖边框,则取决于您想要达到的效果尝试使用:after/:before伪元素,例如

.half {
    width: 50%;
    float: left;
    background: red;
    box-sizing: border-box;
    box-shadow: 0px 0px 3px black;
}

.half:after, .half:before {
    content: "";
    width: 5px; /* or more if you need more space */
    display: inline-block;
}

示例:http: //jsbin.com/imiqak/1/edit


或者您可以使用一些嵌套元素,如下所示:

.half {
    width: 50%;
    float: left;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    padding: 5px;
}

.half p {
    background: red;
    box-shadow: 0px 0px 3px black;
}

示例:http: //jsbin.com/imiqak/3/edit

于 2013-07-31T09:55:28.763 回答
0

尝试这个:

CSS:

<style type="text/css">
.half{
    width: 49%;
    float: left;
    background: red;
    box-sizing: border-box;
}

.half:last-child{
margin-left: 1%;
}
</style>

HTML:

<div class="half">half</div>
<div class="half">half</div>
于 2013-07-31T10:06:53.480 回答
0

margin are considered as outside the box (it's spaces around your box, not in the box). Margins size are not counted as part of the container width.

Indeed, when you type box-sizing: border-box;, you means the size of the box includes the border size, and if you look at this image below, you'll see that the margin are after the border, so it's ignored.

enter image description here

于 2013-07-31T10:00:04.403 回答