Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to horizontally align side by side divs?

I have 3 divs that need to be displayed side-by-side and evenly distributed within the parent div width (which is set to 100% of the window). Whats the best way of doing it?

See example below which is just floating the 3 divs (which just places them one after the other to the left, not what I need).

PS: the list of options is dynamic, i.e. I might have more than 3 divs so the solution should ideally take that into account. Thanks! :)

PS 2: I am using bootstrap so if there is a good way of doing this using bootstrap I'm all for it.

.row {
  width: 100%;
  background-color: #DDD;
}

.option {
  border: 1px solid #BBB;
  float: left;
  padding: 10px;
}
<div class="row">

    <div class="option">
        Box A
    </div>
    <div class="option">
        Box B
    </div>
    <div class="option">
        Box C
    </div>

</div>
like image 257
Wagner Danda da Silva Filho Avatar asked Nov 28 '25 08:11

Wagner Danda da Silva Filho


2 Answers

You can use flex, see fiddle https://jsfiddle.net/Lddyn573/5/

.row {
  width: 100%;
  display: flex;
  justify-content: space-around;
  background-color: #DDD;
}

.option {
  border: 1px solid #BBB;
  padding: 10px;
}
like image 188
Adam Buchanan Smith Avatar answered Nov 29 '25 20:11

Adam Buchanan Smith


Just use flexbox compliments of CSS3. The beauty of it is that so long as there is enough space in the parent element you can add additional children and they will automatically display next to each other. Be mindful that once the parent runs out of space additional child elements will need resize themselves so that they display next to each other. See the below example from W3schools:

 .flex-container {
    display: -webkit-flex;
    display: flex;
    width: 400px;
    height: 250px;
    background-color: lightgrey;
}

.flex-item {
    background-color: cornflowerblue;
    width: 100px;
    height: 100px;
    margin: 10px;
}
    <body>

<div class="flex-container">
  <div class="flex-item">flex item 1</div>
  <div class="flex-item">flex item 2</div>
  <div class="flex-item">flex item 3</div>
</div>

</body>
like image 27
coderrick Avatar answered Nov 29 '25 22:11

coderrick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!