The Box Model

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:

Controlling Overflow

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. */
            
Understanding Position

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;
}
            
Mastering Flexbox

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.


.container {
  display: flex;
  justify-content: center;
}
            
The Magic of Margin Collapse

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; }