gpt4 book ai didi

css - 为什么填充会影响元素的宽度?

转载 作者:太空宇宙 更新时间:2023-11-04 12:51:22 26 4
gpt4 key购买 nike

<style type="text/css">
div{height:400px}
#container{width:100%}
#left10{width:10%;float:left;background:red}
#rest90{width:90%;float:left;background:yellow}
</style>
<div id="container">
<div id="left10"></div>
<div id="rest90"></div>
</div>

如您所见,我的页面上有 2 个 DIV,为了响应,我只按百分比为这 2 个 DIV 分配宽度。现在我希望 #rest90 DIV 中的内容与其左边框有 20px 的距离。但是当我将#rest90 的 padding-left 设置为 20px 时,DIV 将被置换。 fiddle :http://jsfiddle.net/xvnj9oem/

我一直认为 padding 是在一个元素内部,因此不应该影响元素与其他元素的相对位置。但显然我错了,至少在这种情况下。有什么我错过的吗?我是否必须为 #rest90 中的每个元素设置 margin-left 才能实现我的目标?

最佳答案

就像添加到您的 div(或您需要的标签)一样简单

 -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */

看看这个:CSS BOX SIZING

div{
height:400px;
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
}
#container{width:100%}
#left10{width:10%;float:left;background:red}
#rest90{width:90%;float:left;background:yellow; /*just to test padding*/ padding:20px }
<div id="container">
<div id="left10"></div>
<div id="rest90"></div>
</div>

关于css - 为什么填充会影响元素的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26131400/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com