Every element on a web page is a rectangular box. The CSS box model is the set of rules that defines how this box is structured and how it takes up space. Understanding it is the key to creating layouts in CSS.
The box is made of four distinct parts, layered from the inside out:
- The Content Box: Where your text and images appear. Its size is set by
widthandheight. - The Padding Box: The transparent space around the content, inside the border. Set with the
paddingproperty. - The Border Box: The line that goes around the padding and content. Set with the
borderproperty. - The Margin Box: The transparent space outside the border. It pushes other elements away. Set with
the
marginproperty.
Sometimes, the content inside a box is bigger than the box itself. This is called "overflow". The
overflow property is your tool to control what happens in this situation.
The most common values for this property are:
overflow: visible; /* This is the default. Content spills out. */
overflow: hidden; /* The content that spills out is chopped off and becomes invisible. */
overflow: scroll; /* Adds a scrollbar so the user can see the rest of the content. */
The position property allows you to take elements out of the normal document flow and place
them exactly where you want.
While there are several values, one of the most useful is position: sticky;. This allows an
element, like a navigation bar, to scroll with the page until it reaches a certain point, where it will
"stick" to the screen.
To make it work, you must also provide an offset property, like top: 0;, which tells the
element where to stick.
#navbar {
position: sticky;
top: 0;
}
Flexbox is a modern layout mode designed for arranging items in a single dimension (either a row or a column). It makes centering things and creating responsive layouts much easier than older methods.
To start using Flexbox, you set a container element to display: flex;. Then you can use
properties to control the items inside it.
justify-content: controls horizontal alignment.align-items: controls vertical alignment.flex-direction: controls if the items are in a row or column (and in what order).
.container {
display: flex;
justify-content: center;
}
Margin collapse is a confusing but important behavior. When the top margin of a child element touches the top edge of its parent element, that margin doesn't create space inside the parent. Instead, it "escapes" and pushes the parent down.
This can be prevented by creating a "Block Formatting Context" (BFC). A BFC is like a mini-layout environment that contains its children's margins.
There are several ways to create a BFC on the parent element to stop margin collapse, including:
/* Method 1: Use overflow */
.parent { overflow: hidden; }
/* Method 2: Add a border or padding */
.parent { border-top: 1px solid transparent; }