如何从每列的最后一个 div 中获取一个边距
,并为最后一列的所有 div 添加边距
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
div.teste {
margin: 135px auto 0 auto;
width: 300px;
padding: 10px 10px;
overflow: hidden;
border: 2px dashed #000
}
div.teste>h3 {
margin: 0 0 10px 0;
border-bottom: 2px dashed #000
}
div.teste>div {
float: left;
padding: 0 5px;
margin: 0 5px 5px 0;
width: 65px !important;
height: 25px;
text-align: center;
line-height: 25px;
background-color: rgba( 0, 0, 0, 0.4);
}
div.teste>div:nth-child( 4n-1) {
margin: 0;
background-color: #ccc
}
div.teste>div:last-child {
margin: 0;
}
<div class="teste">
<h3>Primeiro</h3>
<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>
最佳答案
我建议使用 Flexbox
布局在这里。包装所有数字 div 并使用 width
应用 display:flex
。
此外,您还需要使用父 div padding
和子 div margin
来正确对齐 div。
h3 {
margin: 0 0 10px 0;
border-bottom: 2px dashed #000
}
div.teste>div {
width: calc(33.333% - 10px);
height: 25px;
text-align: center;
line-height: 25px;
background-color: rgba( 0, 0, 0, 0.4);
margin-bottom: 15px;
}
.teste {
border: 2px solid #ccc;
padding: 15px 15px 0;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
<h3>Primeiro</h3>
<div class="teste">
<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>9</div>
</div>
另一种解决方案是尝试在子 div 上使用边距,并使用 nth-child
选择器从每个 (3n+1) 个子元素中删除边距。此解决方案适用于奇数/偶数两种情况
h3 {
margin: 0 0 10px 0;
border-bottom: 2px dashed #000
}
div.teste>div {
width: calc(33.333% - 10px);
height: 25px;
text-align: center;
line-height: 25px;
background-color: rgba( 0, 0, 0, 0.4);
margin-bottom: 15px;
margin-left: 15px;
}
.teste {
border: 2px solid #ccc;
padding: 15px 15px 0;
display: flex;
flex-wrap: wrap;
}
div.teste>div:nth-child(3n+1) {
margin-left: 0;
}
<h3>Primeiro</h3>
<div class="teste">
<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>
关于html - 最后一个 div 和最后一列的边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58654029/