首页 > 解决方案 > CSS 按钮对齐除最后一个以外的所有 div

问题描述

我想显示对齐以填​​充完整 div 的所有按钮width,除了最后一个。我的代码在下面,但最后一个 div 很短并且正在扩展全宽,我不希望最后一个 div 使用这个。

注意:按钮是动态生成的。

.block {
  width: 400px;
  display: flex;
  flex-wrap: wrap;
}

.button {
  background-color: #cec;
  border: none;
  color: white;
  margin: 15px;
  padding: 15px;
  display: inline-block;
  font-size: 16px;
  flex: 1 0 auto;
}
<div class="block">
  <div class="button"><a href="#">#1 - A LONG TEXT GOES HERE</a>
  </div>
  <div class="button"><a href="#">#2 - ANOTHER LONG TEXT HERE</a>
  </div>
  <div class="button"><a href="#">#3 - SOME TEXT HERE</a>
  </div>
  <div class="button"><a href="#">#4 - SHORT TEXT</a>
  </div>
  <div class="button"><a href="#">#5 - SHORT</a>
  </div>
  <div class="button"><a href="#">#6 - SHORT</a>
  </div>
</div>

标签: htmlcss

解决方案


You can use :last-child selector, it matches every element that is the last child of its parent.

.button:last-child

Or you can also use nth-last-child(1) because nth-last-child(1) equal to last-child selector

.button:nth-last-child(1)

推荐阅读