html - 最后一个 div 和最后一列的边距

标签 html css

如何从每列的最后一个 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>

预期的结果是这样的 example

最佳答案

我建议使用 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/

相关文章:

html - 创建没有后端的联系表?

html - 如何使用 Bootstrap 在 div 后面显示图像?

html - 以响应大小垂直扩展背景

css - 样式特定表而不影响每个表

javascript - 让 div 保持屏幕宽度和高度

javascript - jQuery:将按钮过滤器转换为选择菜单选项?

python - 为什么我的 Flask Web 应用程序未检测到代码更改

css - Facebook 按钮在点击时改变位置

css - 使用 Oracle ADF Mobile 的按钮图像路径

html - 在 twitter bootstrap 导航列表中对齐文本