The CSS box model is an essential concept in web design, defining the structure of every HTML element on a page. It consists of four parts: margin, border, padding, and content. The box-sizing
property plays a key role in controlling how these elements are sized.
By default, an element's width and height only include the content. However, with box-sizing: border-box
, these dimensions also encompass the padding and border, which is crucial for predictable layout behavior.
Example: Creating Three Cards Side by Side
To illustrate this, let's create an example with three cards displayed side by side using inline-block
. Each card will have its own padding, border, and margin, showcasing their effect on the overall layout.
HTML Structure:
<div class="card">Card 1</div>
<div class="card">Card 2</div>
<div class="card">Card 3</div>
CSS Styling:
.card {
width: calc(33.3% - 10px);
height: 100px;
padding: 10px;
border: 1px dotted tomato;
color: tomato;
display: inline-block;
box-sizing: border-box;
box-shadow: 5px 15px 5px 2px #eaeaea;
border-radius: 4px;
}
.card:nth-child(1),
.card:nth-child(2) {
margin-right: 5px;
}
In this example, each .card
is styled with display: inline-block
, which allows the cards to sit side by side. The box-sizing: border-box
ensures that the padding and border are included in the total width and height of each card. The margin creates space between the cards. This example is a simple yet effective way to demonstrate how the box model's components interact and affect an element's dimensions and spacing on a webpage.