CSS either show all elements in a single row or each element on a new row

Viewed 99

I have four buttons with varying content lengths. I want all buttons to have the same dimensions as the largest button. They should all be displayed in a single row if there is sufficient space otherwise each button should be displayed on a new row. I have attached a diagram below.

Paint diagram of intended element layout

My HTML code is

<div class="answers">
    <button class="button">A</button><br>
    <button class="button">B</button><br>
    <button class="button">C</button><br>
    <button class="button">D</button><br>
</div>

I have given the following CSS properties to the container

.answers {
    display: inline-flex;
    flex-direction: column;
    justify-content: center;
    flex-wrap: wrap;
}

This ensures that all the buttons are the same width but it always displays them on four lines even when there is room to have them all on a single row.

TLDR:

I need a way to make sure all the buttons have the same width as the largest button, I do not know this value as the buttons can be updated with new content.

I then need to calculate if these four buttons can fit horizontally on the screen and if not display them vertically avoiding a situation where I might have a grid of 2x2.

1 Answers

One approach can be like this (you can use jquery to calculate width for all buttons according to the text in the largest button)

let maxWidth = 0;

$('.button').each(function(){
 const width = parseFloat($(this).css('width'));
 if(width > maxWidth) {maxWidth = width}
})

$('.button').css('width', maxWidth +'px');
.answers {
    display: inline-flex;
    justify-content: center;
    table-layout: fixed;
    flex-direction: row;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="answers">
    <button class="button">small</button><br>
    <button class="button">s</button><br>
    <button class="button">large</button><br>
    <button class="button">the largest</button><br>
</div>

Related