So far we’ve been styling the look of a part’s contents — things like color and text. Now let’s widen our view and control the size of the parts themselves. We’ll start with the most basic: “width” and “height.”
Let’s write some
.box {
width: 300px;
height: 200px;
background-color: teal;
}This means “a box 300 pixels wide and 200 pixels tall.” Add a background color and the rectangle at the size you set shows up clearly.
width… the horizontal sizeheight… the vertical size
Change the numbers and the box’s size changes right along with them.
width is horizontal, height is vertical. The rectangle lands exactly at the size of the numbers you write.Grow and shrink to fit the screen
Instead of px, use % (percent) and the size is set as a proportion of the surroundings.
.box {
width: 50%;
}This means “half the width of the surroundings.” Wide when the screen is wide, narrow when it’s narrow — it grows and shrinks automatically. Pages that hold up on both phones and computers are built with proportional settings like this.
The “surroundings,” to be precise, are the parent that wraps the part (the box one level out). Inside a box that fills the screen, it becomes half the screen; inside a box that’s 400px wide, it becomes 200px.
50% — exactly half the width. Change the parent’s size and this width changes right along with it.Set just a minimum height: min-height
We just said “don’t over-set height,” but sometimes you want “at least this much, please.” That’s when min-height (minimum height) comes in.
.hero {
min-height: 300px;
}Even with little content, it secures a height of 300px, and when content grows it stretches to match. Unlike height, there’s no worry of spilling over, so when you want to give something height, this is the safe choice.
min-height, even with a single line of text.Prevent “too wide” with max-width
Use max-width (maximum width) and you can set a cap: “you may grow up to here, but no wider.”
p {
max-width: 500px;
}Unlike width, it still shrinks properly when the screen is narrow, but even when the screen gets wide it won’t grow past 500px. It’s the standard way to keep text from stretching too long across a big screen and getting hard to read.
width.Set width by character count: the ch unit
Besides px, you can set text width with a unit called ch.
p {
max-width: 32ch;
}ch is a unit that takes the width of one character as 1 (short for character). So 32ch means “roughly the width of 32 characters.” Since you can set width based on the number of characters per line, it’s the perfect unit for preventing “the line is too long to read comfortably.”
Summary of this lesson
- Horizontal size is
width, vertical size isheight - Use
%and it grows and shrinks to match the surroundings - Don’t over-set height. When you want it, set only a minimum with
min-height - Cap the maximum with
max-width, and for text thechunit is handy too
