CSS Size Summary
CSS size usually means width and height. Width controls how wide an element is. Height controls how tall an element is.
.box {
width: 300px;
height: 150px;
}
Width
Width controls how much horizontal space an element takes up. A box with width: 300px; will be 300 pixels wide.
.box {
width: 300px;
}
Width is used constantly in real web layouts. It can control the size of cards, buttons, images, sidebars, wrappers, and sections.
Height
Height controls how much vertical space an element takes up. A box with height: 150px; will be 150 pixels tall.
.box {
height: 150px;
}
Height is useful, but it should be used carefully. Text, images, and screen sizes can change. If the height is too small, the content may not fit well.
Block Elements
Block elements usually take up the full width available unless you give them a specific width. Common block elements include div, p, h1, h2, section, header, and footer.
div {
width: 300px;
}
When a block element has a width, padding can make the visible box larger unless you use box-sizing: border-box;.
.box {
box-sizing: border-box;
width: 300px;
padding: 20px;
}
With box-sizing: border-box;, the padding is included inside the size of the block. This makes the box easier to control.
Inline Elements
Inline elements sit inside a line of text. Common inline elements include span, a, strong, and em.
Inline elements do not behave like normal boxes for width and height. Setting width or height on an inline element usually does not work the way it does on a block element.
span {
width: 300px;
height: 100px;
}
Padding can still be added to inline elements, but it does not create a normal block-sized box. If you need width, height, and padding to behave like a regular box, use display: inline-block; or display: block;.
span {
display: inline-block;
width: 300px;
padding: 20px;
}
Common Size Values
CSS sizes can use pixels, percentages, and other units. Pixels are fixed. Percentages are based on the size of the parent element.
.fixed-box {
width: 300px;
}
.fluid-box {
width: 100%;
}
A fixed width stays the same size. A percentage width can grow or shrink with the page or parent box.