除了最后一个div外,所有div的CSS按钮都对齐



我想显示所有对齐的按钮,以填充整个divwidth,除了最后一个按钮。我的代码在下面,但最后一个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>

短类可以有单独的类。

.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;
}
.short {
max-width: 20vw;
}
<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 short"><a href="#">#5 - SHORT</a>
</div>
<div class="button short"><a href="#">#6 - SHORT</a>
</div>
</div>

您可以使用:last child选择器,它匹配其父元素的最后一个子元素。

.button:last-child

或者,您也可以使用第n个最后子项(1(,因为第n个最近子项(2(等于最后子项选择器

.button:nth-last-child(1)

您可以使用最后一个子伪类仅针对按钮类的最后一个元素。

.button:last-child {
max-width: max-content;
}

工作示例:

.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;
}
.button:last-child {
max-width: max-content;
}
<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>

最新更新