Skip to main content
Crowdfunding
Python + AI for Geeks
Practice

Designing Layouts with the Box Model

Let's explore layout design techniques using the box model 🙂


Center Alignment​

To place a block element in the center of the screen, use margin: 0 auto.

The auto value only applies horizontally, not vertically.

CSS
.box {
width: 300px;
margin: 0 auto; /* Top and bottom margins are 0, and left and right margins are automatically adjusted to center horizontally */
}

Card Design​

When designing card-style elements, use padding, border, and margin.

CSS
.card {
padding: 20px; /* Inner spacing */
border: 1px solid #ddd; /* Border */
margin: 20px 0; /* Outer spacing */

/* Shadow effect */
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
/* 0: horizontal offset, 4px: vertical offset, 8px: blur radius, rgba: color and transparency */
}

Utilizing box-sizing​

By default, the width of a box refers only to the width of the content.

So if you add padding or border, the total width of the box increases.

To include padding and border within the specified width of the element, use the box-sizing: border-box property.

CSS
.border-box-example {
box-sizing: border-box; /* Specifies width including padding and border */
width: 200px; /* Element's width is 200px */
height: 200px; /* Element's height is 200px */
padding: 20px;
border: 10px solid black;
}

In this case, the actual visible width of the box remains 200px, with padding and border included within this width.

Using box-sizing: border-box prevents the element from becoming larger than expected due to padding and border.

Want to learn more?

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