Creating A Split Component

Photo by  Cassie Matias  on  Unsplash For the longest time, floats were the go-to tool for putting two things next to each other. Unfortunately, since this is not what floats were designed for, this created as many problems as it solved. Luckily, modern CSS makes this much easier to solve. Let's take the following layout: In this layout we need to be able to split the two children into fractional parts of the partents width while maintaining a gutter between them. Let's say we start with the following basic markup. What we need to do is build a Split component that will fractionally split the width of the outer dive between the div  that is wrapping the h2  and span  and the Form  component. There is a couple of ways we could tackle this, but the easiest would be to use CSS grid: In the above code, first we set the display  property to grid  and set the gap property to 1rem . This will create a grid container that puts a gap of 1rem  between each of the children of the Split component. In the final line we are setting the   grid-template-columns  property. The grid-template-columns property allows us to define how many column tracks we have and how wide they should be. We define the width of each column track using any valid CSS size unit, and the quantity of tracks is determined by how many sizes we assign to the property. For example, if we wanted three column tracks of 30px , 50% , and 2rem , It would look like this: Looking back at the Split component above, you will notice that we are using a special size unit that you might not recognize. The fr unit is a unique size unit only available when using CSS grid. The fr unit (or the fraction unit as it is sometimes called) says to the browser, "give me X fraction(s) of the remaining space available." If we set the grid-template-columns to be 1fr 1fr , which will result in two columns with a 50/50 split, like this: It is essential to distinguish that fr is not the same as % . When we use % , we are saying give me a percentage of the total width of my parent component. What that doesn't take into account is the gutter between the elements. So using 50% 50% would result in an overflow, where 1fr 1fr would not. The mockup above doesn't call for a 50/50 split though. The requirement is to split it into thirds, with the first column taking up only 1/3. Also, hard-coding column tracks do not make for a useful primitive. We need something more configurable that we can adjust to the situation. So let's make the following changes: Now, instead of hard-coding values, we have named our fractions according to the ratio we want them to take and now we can update our FormSideBar component like this: Now we have a component that lets us fractionally split anything among two children.  The Split component works great for any time you want to put two elements next to each other, such as for side bars.

Thumbnail Image of Tutorial Creating A Split Component