Center a Column With Auto Margins

In the last lesson, you gave the Coming Up section a green background and watched its heading’s top margin leak out above it until padding held it in. That section still runs from one edge of the window to the other. In a wide window, the cards stretch with it, well over a thousand pixels wide for a few short lines of text.

In this lesson, you’ll give the column of events a width it won’t grow past, and then center it on the page with auto margins. You’ll also see why text-align: center, which already centers the banner’s heading, can’t do this job. Start with the width.

Stop the Column From Growing

Rosa would like the events to sit in a column down the middle of the page, like the notices on the garden’s board. Open upcoming.html in a window about as wide as a laptop screen, and look at the Coming Up section:

The events page at 1280 pixels wide, with the light green Coming Up section and both event cards stretching across the whole window.
The Section Fills the Whole Window

The green section and both cards run the full width of the window. You saw why in Follow Normal Flow. A block box takes the full width of its parent, and the cards fill the section in the same way. So to make the column narrower, give the section a width of its own.

You gave the cards width: 300px in Size Boxes With border-box, and width: 700px would narrow the section the same way. However, a fixed width doesn’t give way. In a window narrower than 700 pixels, the section would stay 700 wide and stick out past the window’s edge.

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.