Tutorials on Layout Composition

Learn about Layout Composition from fellow newline community members!

  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL
  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL

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

How to Build a Composable Stack Component

Photo by  Sean Stratton  on  Unsplash One of the simplest and yet most common layout patterns found on the web is putting one element on top of another element with consistent space between them. From form labels, to paragraphs of text, to social media feeds. They all need to stack one thing on top of another with uniform space between them.  Let's say we are building the following component: As you will notice, we have a few parts to this widget. There is a title section and a form section made up of two input groups and a button. The one thing that they all have in common is that they follow the same pattern. They all stack vertically with space between them. Here is the same mockup with the different space sizes pointed out. What we need is a way to enforce that all the items will stack in the block direction. We also need a way to provide consistent space between the elements without creating space around the stacked elements themselves. That way, the stack can remain composable in any other environment. (I will be using Styled Components  in these examples, but everything can easily be translated to any flavor of CSS, including vanilla CSS.) Let's start with some basic markup. And this is what that looks like: The first problem we want to solve is to get the labels to stack on top of our inputs. This problem is easily solved with a single line of CSS: We create a new Stack component and set the display property to grid , thereby implicitly setting a single column track for items inside the Stack. Each item that is placed in that column creates an implicit row. We can then use this new Stack a component like this: Our component has already taken a major step in the right direction: The first thing you will notice is that not only are the labels stacked on top of each other, they also now take up the entire width of the column. All we need to do now is set the space between the items. We set the space between items using the gap property, which takes any valid sizing unit, such as px , % , or rem . To make it configurable via props, we will take advantage of the styled-components string interpolation and derive the value from props, like this: (If the syntax above is unfamiliar to you, it uses tagged template literals that are part of ES2015. You can find out more about tagged template literals over at MDN ) When we use styled.div we are calling a tagged template literal that will let us pass in a function inside the ${} that gives us access to the component props . We can then customize what the CSS looks like depending on the value of the props . The above code takes the value of the gutter prop and uses that as the value of the gap property. We could have used any name for the prop , such as space or even gap . I chose to use gutter as it is a common term when talking about page layouts. If no value is passed to gutter , it will fall back to 1rem . This means we can rewrite our Subscribe  component like this: And now our component looks like the final version: We have a component that will universally stack all of its children and will separate them via a configurable value that passed into the gutter prop. We could stop here, but I would recommend one more tweak to the gutter prop. Right now, we are allowing any value passed into the gutter. It is considered best practice to adopt a spacing scheme when you are laying out items on the web for consistency. Choosing a good spacing scheme is beyond the scope of this post. For simplicity, let's use a spacing scheme based on t-shirt sizes and looks something like this: Now, all we need to do is adjust our Stack component slightly, like this: and update our Subscribe  component like this: The Stack component is a straightforward yet powerful tool that allows you to compose vertical stacks of elements on your page.  

Thumbnail Image of Tutorial How to Build a Composable Stack Component

I got a job offer, thanks in a big part to your teaching. They sent a test as part of the interview process, and this was a huge help to implement my own Node server.

This has been a really good investment!

Advance your career with newline Pro.

Only $30 per month for unlimited access to over 60+ books, guides and courses!

Learn More

Composing Layouts

Composition, simply put, is when you build something greater than the sum of its parts. For example, an organism is composed of organs, which are composed of organ parts, which are composed of cells, which are composed of atoms. A musical composition can be broken down to nothing more than masterfully applying rhythm and tempo to 12 unique notes, creating all of our musical masterpieces. Composition also applies to web layout. Complex layouts can be broken down into simpler "layout primitives," as described by Heydon Pickering . These layout primitives are single-purpose layout components that do one thing and one thing well. It is by strategically combining these primitives that we achieve more complex layout structures. Let's take the below hero layout, for example: Naively we might choose to do something like this: Several CSS methodologies like BEM , Object-Oriented CSS(OOCSS) , or Atomic CSS  can help create more consistent class names and are generally useful in managing our CSS style sheets at scale. Unfortunately, those methodologies can only get you so far. When we approach our component's layout as something unique for each component, we miss a fantastic opportunity to define a consistent visual structure in our application. Instead, all of our layouts are treated as unique things that need to be built from scratch over and over again. Instead of looking at our Hero component as one isolated element, let's break it up into smaller, single-purpose layout components, like this: (Don't worry about how these components are implemented right now. Just focus on the intended outcome of the components.) Then we can apply these layout components like this: In code, this would translate to something like this: These "layout primitives" can be applied in a signup form, a blog post feed, a feature page, or any other part of our web page. Most of the layouts we use every day are not that unique and can be broken down, at least in part, to one of a handful of layout patterns. Thinking in terms of layout composition can feel strange at first. Probably one of the more difficult parts is knowing **where** you should apply your style rules in your component.

Thumbnail Image of Tutorial Composing Layouts

CSS Reset For Composable Layouts

The styles that we write are not the first styles that get applied to our app. Before a single line of our CSS is used, the browsers will apply their user-agent style sheets. Unfortunately, there is no rule that requires any of the browsers to use the same style sheet for their user-agent. For this reason, CSS Resets have been a valuable tool to help developers provide consistent styling on the web. A CSS Reset is nothing more than a style sheet you bring in before the rest of your app's styles, either as a separate style sheet or tagged onto the beginning of your style sheet. This style sheet's goal is simply to provide a base from which you can consistently apply CSS across browsers. Some resets are aggressive and remove all styles from all elements. Others try to "normalize" all the user-agent style sheets of the various browsers. Luckily, there is currently less inconsistency across the browsers than would justify aggressive resets. Still, from a layout perspective, there is a need to override the browser default styles to make compositional layout possible. It makes sense to look at what you need to reset in the browser's user-agent style sheets to achieve this goal. The first thing to set is the box-sizing property on all elements and pseudo-elements to border-box : Setting the box-sizing property to border-box on all elements and pseudo-elements allows for a more intuitive developer experience since the size of the element will be calculated from border to border instead of the default, which is content + padding + border. After that, we remove any margins from all the elements. Doing this allows elements the ability to better control the space between their child elements. It is difficult to layout items correctly if they already have a built-in margin that you have to override. From there, we remove the padding and list style from ul and ol elements. A common thing that most people do when working with lists is remove the default padding and list styles added by browsers. Since this is pretty much universally done every time one styles a list, I like to do it once and get it done with. You will notice that we are using the attribute selector to remove the padding and list style only if the class attribute is set. Doing this will allow our lists to be reset if we are actively styling the element using the class attribute. By doing it this way, our list elements retain their default styles when we use the pure ul and ol tags without styling applied. Next, we set the min-block-size of the body to be 100vh It is helpful to have the body take up the entire viewport even if its content does not. Next, we set our images to be block-level elements instead of inline-level elements and then set their max-inline-size to 100% . Setting the max-inline-size to 100% makes our images responsive by default and treats images as block-level elements, which is how most people use img tags. Finally, we set the max-inline-size of text-based tags to be 60ch . The ch unit is approximately the width of the 0 character of the font family in use. In any given font family, each character can either be very wide like the letter W or very skinny like the letter l. The 0 is neither the widest nor skinniest character in a font family and is a good proxy for a character width. We use 60ch because a large amount of research has gone into finding the optimal line lengths for readability. You can check out the work done over at material.io to read more about optimal line lengths, but for brevity, 60 characters is a good default cap on the inline size of the text. With these resets in place, we have now primed the browser to let us start building composable layouts.

Thumbnail Image of Tutorial  CSS Reset For Composable Layouts