Skip to main content
Practice

Adding Space to Elements

If HTML elements are too close to each other, the webpage can look cramped, while if they are too far apart, the webpage can look empty.

So, how can we control the space between elements? We use margin and padding, which we have learned before, to adjust that space.


margin

It is used to adjust the outer space around an element. The margin refers to the empty space surrounding the element, and you can think of it as "the empty space around an element".

It is like leaving an empty space between books.

The margin can be used to add or remove space around elements to control the gaps between them.

Margins can be specified in units like pixels (px) or percentages (%).


padding

It is used to adjust the inner space inside an element. The padding refers to the empty space inside an element, and you can think of it as "the empty space inside an element".

This is akin to leaving space between a book cover and the book's pages.

Padding allows you to add or remove inner space, adjusting the gap between the element's content and its border.

Inner padding can also be specified in units like pixels (px) or percentages (%).


For example, the following CSS code sets the margin and padding for a <div> element:

Setting margin and padding
div {
margin: 10px;
padding: 20px;
}

The code above adds a 10-pixel margin around the <div> element and applies a 20-pixel padding inside the <div> element.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.