仅使用百分比,如何创建适合指定容器的相等边距?我在下面尝试过,但未能达到相等的利润。
body {
padding:0;
margin:0;
background:#000;
}
.category_wrap div {
float: left;
width: 49%;
background: red;
height: 50px;
margin-left: 1%;
margin-bottom: 1%;
overflow: hidden;
}
<div class="category_wrap">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
</div>
JSFiddle link
.category_wrap div:nth-child(even) {
margin-right: 1%;
}
我还在div
列上添加了48.5%
宽度以补偿边距。
48.5
来自 (100-3(/2,其中 3 是每行左/右边距的总体百分比。
另一种选择是将其包裹在container
中,给它一个98%
的宽度并给它margin: 0 1%;
,然后给奇数div
列一个margin-right: 1%
;
在 css 中添加媒体查询以解决您的问题
不完全确定您要寻求的确切效果,但是通过在 CSS 中使用第 n 个子选择器来平衡列中间的边距与容器div 左右两侧的边距,@knitevision是正确的。
这是在代码笔中
.HTML:
<div class="category_wrap">
<div class="container">1</div>
<div class="container">2</div>
<div class="container">3</div>
<div class="container">4</div>
</div>
.CSS:
body{
padding:0;
margin:0;
background: black;
text-align: center;
}
.category_wrap div{
float: left;
background: red;
width: 48.5%;
height: 50px;
}
.container:nth-child(odd){
background: blue;
margin: 0 .5% 0 1%;
}
.container:nth-child(even){
margin: 0 1% 0 .5%;
}
就像@knitevision的答案一样,如果你在三个排水沟中寻求 1% 的余量,48.5% 成为每个div 宽度的神奇数字:(100-3(/2。
此外,在高度参数中使用 % 边距时要小心,因为 1% 的高度不等于宽度的 1%,并且您的边距看起来会偏。
延伸阅读:第 n 个孩子如何工作
box-sizing: border-box is the best way to do this. It changes the width and height to include the padding and border.The box-sizing property is used to tell the browser what the sizing properties (width and height) should include.
小提琴演示
https://jsfiddle.net/DhwaniSanghvi/ckvpc0to/
<div class="category_wrap">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
</div>
body {
padding:0;
margin:0;
background:#000;
}
.category_wrap {
overflow: hidden;
}
.category_wrap div {
float: left;
width: 50%;
background: red;
height: 50px;
overflow: hidden;
padding: 10px;
border:2px solid black;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}