简体   繁体   中英

CSS buttons align for all divs except the last one

I want to display all buttons aligned to fill full div width , except for the last one. My code is below, but the last div is short and is expanding full width, I don't want this for the last one.

NOTE: The buttons are dynamically generated.

 .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>

You can have separate classes for the short ones.

 .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>

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)

You can use last-child pseudo-class to target the last element only of you button class.

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

Working Example:

 .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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM