Html CSS:宽度百分比和边框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11070071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CSS: Width in percentage and Borders
提问by user1355300
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?
我已经以百分比定义了容器的宽度。我想添加一个边框(宽度右侧 3px),因为容器宽度以 % 为单位,而边框宽度以 px 为单位,我该如何调整容器的宽度?
<div class="wrap">
<div class="left">...</div>
<div class="right">...</div>
</div>
.wrap{
width:100%;
}
.left{
width:30%;
}
.right{
width:70%;
}
I'd like to add 3px border on the right side of .left. For example:
我想在 .left 的右侧添加 3px 边框。例如:
.left{
width:30%;
border:3px solid #000;
}
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.
由于我在 % 中定义了宽度,重新调整 .left 宽度的最佳方法是什么。我可以粗略地将宽度减小到 29%,但我想精确地做到这一点。
回答by Bojangles
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 includesdimensions 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.
使用box-sizing: border-box
物业。它修改了盒模型的行为,将内边距和边框视为元素总宽度的一部分(但不是边距)。这意味着元素的设置宽度或高度包括为填充和边框设置的尺寸。在您的情况下,这意味着元素的宽度和边框的宽度将消耗 30% 的可用空间。
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;
}
More information can be found on the MDNand Quirksmode.
更多信息可以在MDN和Quirksmode上找到。
According to Quirksmode, using the 3 vendor prefixes above (-moz-
, -webkit-
and -ms-
), you get support for all browsers, even IE8.
根据 Quirksmode,使用上面的 3 个供应商前缀(-moz-
,-webkit-
和-ms-
),您可以获得对所有浏览器的支持,甚至 IE8。
回答by Emil Stenstr?m
The easiest cross-browser way is to NOT set the border on the outer divs, and instead set it on a NEW div inside .left
. Simple, and works well.
最简单的跨浏览器方法是不要在外部 div 上设置边框,而是将其设置在.left
. 简单,而且效果很好。
回答by Sarfraz
That's a bit tricky but check out this post on a way to get around it:
这有点棘手,但请查看这篇文章以解决它:
The box-sizing
property may also be of interest to you, check this out:
box-sizing
您可能也对该物业感兴趣,请查看:
回答by Sarfraz
Just change px
to vw
like
只要改变px
对vw
喜欢
border-width: 10px;
to
到
border-width: 10vw;
Its do whats percentage do....
它做什么百分比做什么....