Max Width and Centering

A fixed width is a problem on narrow screens: a card 384 pixels wide doesn't fit on a phone. What we want is a card as wide as there's room for, but never wider than 384 pixels. That's the max-width property, which you used in the final project of the CSS course. In Tailwind, it's set by the max-w-* classes, with named sizes:

ClassCSSWidth
max-w-xsmax-width: 20rem;320 px
max-w-smmax-width: 24rem;384 px
max-w-mdmax-width: 28rem;448 px
max-w-lgmax-width: 32rem;512 px
max-w-xlmax-width: 36rem;576 px
max-w-2xlmax-width: 42rem;672 px
max-w-prosemax-width: 65ch;about 65 characters

You know the size names from the font sizes: xs is extra small, sm small, lg large and xl extra large. The only new one is md, medium, the size between sm and lg. Bigger ones go on up to max-w-7xl. max-w-prose is meant for text: the unit ch is the width of the digit 0 in the element's font, so the lines are about 65 characters long, which is comfortable to read.

On wide screens, the card then needs to be in the middle. In the CSS course, you wrote margin: 0 auto. In Tailwind, it's mx-auto:

.mx-auto {
	margin-left: auto;
	margin-right: auto;
}

(Tailwind writes it as margin-inline: auto, which means the same in a language written from left to right.) The browser splits the free space next to the element equally between its left and right margins. That's why it only works for an element that's narrower than its parent: one with a width or a maximum width. And don't confuse it with text-center: that centers the text inside a box, while mx-auto centers the box itself.

Instructions

In the card's class attribute, replace w-96 with max-w-sm. In a wide preview, the card stays 384 pixels wide, but click 375 px again: now it fits.

Add the class mx-auto to the card, which moves it to the middle of the page. In a narrow preview, there's little free space next to the card, so the change is small: try 768 px.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

5/9