J. Ayo J. Ayo - 2 months ago 13
CSS Question

How do I horizontally align a group of radio buttons (and labels) when using display:flex to stack them side by side

I have used

display:flex
to style a number of radio buttons so that they appear side by side, rather than in one long column. I thought by using
margin:auto
in combination with this, the child elements would appear grouped but in the center of the page horizontally. Clearly this isn't the case, so any help would be appreciated please.

Here is what I have currently:



input[type="radio"] {
display: none;
}
input[type="radio"]:checked + label {
background-color: red;
display: inline-block;
line-height: 4vw;
text-align: center;
width: 18vw;
}
label {
background-color: orange;
display: inline-block;
line-height: 4vw;
color: white;
text-align: center;
width: 18vw;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<section style="display:flex; margin:auto;">
<div>
<p>Amount:</p>
</br>
<input type="radio" name="Amount" id="Amount1" value="single" / checked>
<label for="Amount1">Amount 1</label>
</br>
</br>
<input type="radio" name="Amount" id="Amount2" value="multi" />
<label for="Amount2">Amount 2</label>
</div>
<span style="width:5vw;display:inline-block"></span>
<div>
<p>Term:</p>
</br>
<input type="radio" name="Term" id="Term1" value="0" / checked>
<label for="Term1">Term 1</label>
</br>
</br>
<input type="radio" name="Term" id="Term2" value="1" />
<label for="Term2">Term 2</label>
</div>
<span style="width:5vw;display:inline-block"></span>
<div>
<p>Phone:</p>
</br>
<input type="radio" name="Phone" id="Phone1" value="0" / checked>
<label for="Phone1">Phone 1</label>
</br>
</br>
<input type="radio" name="Phone" id="Phone2" value="1" />
<label for="Phone2">Phone 2</label>
</div>
</section>





I have used viewport width throughout the project, as I have further CSS styling to change element sizes based on media queries. So I need a solution that still keeps this styling if possible.

Answer

Using the following should help:

justify-content: center 

On the display:flex class.

Source: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Comments