My Code:
.container {
width: 100px;
margin: 0 auto;
padding: 0 10px;
background: red;
}
/* this is inside the container */
.inside {
width: 100%;
height: 100px;
background: blue;
margin: 0 -10px;
}
结果
预期成果
我做错了什么?我已经看到Bootstrap网格做了类似的事情。
快速更新。抱歉解释不佳。进一步说明:
边距: 0 -10px;用于向左侧和右侧添加边距,但右侧不执行任何操作。
对于.inside
,width: 100%
只覆盖.container
填充内部的空间。您需要将额外的 20px 添加回其宽度:
.container {
width: 100px;
margin: 0 auto;
padding: 0 10px;
background: red;
}
/* this is inside the container */
.inside {
width: calc(100% + 20px);
height: 100px;
background: blue;
margin: 0 -10px;
}
<div class='container'>
<div class='inside'></div>
</div>
CSS margin
属性的语法为:
margin: (all|vertical horizontal|top right bottom left)(unit);
这意味着您的声明
margin: 0 -10px;
正在使用vertical horizontal
语法 - 即您将-10px
边距应用于元素的两侧,而不仅仅是右侧。若要解决此问题,请使用完整语法:
margin: 0 -10px 0 0;
使用此选项设置右边距:
margin:0 -10px 0 0;
// top, right, bottom, left