问题描述
我已经用百分比定义了容器的宽度.我想添加一个边框(宽度右侧为3px),因为容器的宽度为%,而边框的宽度为px,如何调整容器的宽度?
I've defined widths of the containers in percentage. I'd like to add a border (3px on right side of a width), since container width is in % while the border width is in px, how can I adjust the width of the container?
<div class="wrap">
<div class="left">...</div>
<div class="right">...</div>
</div>
.wrap{
width:100%;
}
.left{
width:30%;
}
.right{
width:70%;
}
我想在.left的右侧添加3px边框.例如:
I'd like to add 3px border on the right side of .left. For example:
.left{
width:30%;
border:3px solid #000;
}
由于我已经在%中定义了宽度,所以重新调整.left宽度的最佳方法是什么.我可以将宽度大致减少到29%,但我想精确地做.
Since I have defined width in the %, what is the best way to re-adjust the width of the .left. I can roughly decrease the width to 29%, but I want to do precisely.
推荐答案
使用box-sizing: border-box
属性.它修改了框模型的行为,以将填充和边框视为元素总宽度的一部分(但不包括边距).这意味着元素的设置宽度或高度包括为填充和边框设置的尺寸.在您的情况下,这意味着元素的宽度及其边框的宽度将占用30%的可用空间.
Use the box-sizing: border-box
property. It modifies the behaviour of the box model to treat padding and border as part of the total width of the element (not margins, however). This means that the set width or height of the element includes dimensions set for the padding and border. In your case, that would mean the element's width and it's border's width would consume 30% of the available space.
对它的支持并不是完美的,但是,即使不是所有现代浏览器,供应商前缀也将吸引大多数人.
Support for it isn't perfect, however vendor prefixes will catch most if not all modern browsers:
.left {
width: 30%;
border: 3px solid #000;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
-ms-box-sizing: border-box;
box-sizing: border-box;
}
更多信息,请参见 MDN 和.
根据Quirksmode ,使用上面的3个供应商前缀(-moz-
,-webkit-
和-ms-
),您将获得对所有浏览器(甚至是IE8)的支持.
According to Quirksmode, using the 3 vendor prefixes above (-moz-
, -webkit-
and -ms-
), you get support for all browsers, even IE8.
这篇关于CSS:以百分比和边框表示的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!