No Time Dad

A blog about web development written by a busy dad

CSS Split div Evenly

Searching for “css split div evenly” will return a tsunami of different techniques for allowing two div elements to each occupy 50% of a parent element. Which I think is something a lot of people struggle with when working with css. There are many different ways to achieve the same thing. Some are more right than others. I think the modern css approach would involve either flexbox or grid.

I’m focusing on what I think are two of the easiest to understand and quickest ways to accomplish this. The end result should conceptually look something like the below.

Left
Right

Flexbox

<div class="wrapper">
  <div class="block">Left</div>
  <div class="block">Right</div>
</div>
.wrapper {
  display: flex;
  flex-wrap: wrap;
}

.block {
  flex-basis: 50%;
}

This first example uses flexbox to split the space between the divs evenly. It does this by creating a flexbox container on the parent div, then uses flex-basis in the child divs to set their size. Which is 50% in this case since there’re two child divs. This example will only work if both child elements have the block class applied.

One of the major drawbacks to this approach is that I have to remember what flex-basis does. Its name doesn’t exactly give away the fact that it’s used to set the size of a flexbox item. I usually find myself searching for its definition when I need to fill space with flexbox.

The other issue I have with this approach is that I need to apply the block selector to each element for it to work. With that being said, this selector could easily be renamed to left or right with flex-basis: 50% inside of it. Which is a good solution, especially since I’d likely be applying custom styles to each side independent of the other.

Grid

<div class="wrapper">
  <div>Left</div>
  <div>Right</div>
</div>
.wrapper {
  display: grid;
  grid-template-columns: 1fr 1fr;
}

The second approach uses css grid to allow each child div to occupy 50% of their parent’s width. It does this by creating two columns via grid grid-template-columns. Using 1fr for each column allows them to take all of the available space in the parent container. Giving the grid-template-columns property a value of 1fr 1fr means that I want two columns that’ll take up as much space as possible in the parent container. Which naturally defaults to a 50/50 split since there’re two columns.

Using grid is my favorite approach. It uses less code to accomplish the same result as its flexbox counterpart, and all of the css logic to handle the 50/50 split is in the parent selector. This means that the child selectors only need to be concerned about their internal styles and spacing.

Both of these are great approaches. They’ll work across most browsers, and require a minimal amount of css to achieve the the 50/50 split.