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>

Upvotes: 3

Views: 53

Answers (3)

coderrick
coderrick

Reputation: 1011

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>

Upvotes: 1

dhh
dhh

Reputation: 4337

You can make use of the Bootstrap Grid layout:

.option {
  border: 1px solid #BBB;
}
<?php
// whatever $items contains...
$items = [];

$columnWidth = floor(12 / count($items)) ?: 1;
?>

<div class="row">

    <div class="option col-md-<?php echo $columnWidth;?>">
        Box A
    </div>
    <div class="option col-md-<?php echo $columnWidth;?>">
        Box B
    </div>
    <div class="option col-md-<?php echo $columnWidth;?>">
        Box C
    </div>

</div>

The .row CSS should not be needed if you include bootstrap css.

However, that $columnWidth calculation will only work for a maximum of 12 items (that is the maximum number of columns, bootstrap supports per row) and will only result in full-width rows if the number of items is a divisor of 12 (e.g. 1, 2, 3, 4, 6, 12).

Upvotes: 0

Adam Buchanan Smith
Adam Buchanan Smith

Reputation: 9439

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;
}

Upvotes: 2

Related Questions