Center Anything in Both Directions

You can now line up items with flexbox and lay out rows and columns with grid. This section puts the two to work on the layouts most sites need, starting with one that many people fight with: putting something in the middle of a box both ways.

Rosa wants the seed swap page to open like a poster, with its heading in the middle of a banner as tall as the window. In this lesson, you’ll center that heading with flexbox, then with grid in two lines, and you’ll see why centering needs a container with height to spare. Start with the left-to-right direction.

Center the Heading Across

The seed swap page in the starter folder wraps its <h1> in <div class="swap-banner">, the same markup as the events banner, but layout.css has no rule for it yet. So the heading sits at the left of the banner.

A programmer’s first try is often text-align: center, and on this full-width heading, it would put the words in the middle. However, text-align moves only the text inside a box, never the box itself. A heading with a width shows the difference. To see it, add this rule at the end of layout.css:

Language: CSS
.swap-banner h1 {
  width: 25rem;
  text-align: center;
}

Save, and in Chromium, the words sit in the middle of a 400-pixel box. The box itself stays at the banner’s left edge. Select the <h1> in the Elements panel, and its highlight shows the box:

The seed swap page with the Spring Seed Swap heading highlighted, its words centered in a 400-pixel box that sits at the banner's left edge, empty space to its right.
Centered Words in a Box That Stays at the Left

Now delete the rule.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.