June 3, 2024
Understanding the Box Model
The CSS box model is a fundamental concept that describes how elements are structured and displayed on a web page. It consists of four components: content, padding, border, and margin. Understanding the box model is crucial for controlling the layout and design of web elements.
Margins, Padding, and Borders
Each of these components can be controlled using CSS properties:
margin: 20px;
margin-top: 10px;
margin-right: 15px;
margin-bottom: 20px;
margin-left: 25px;
/* Shorthand */
margin: 10px 15px 20px 25px;
padding: 20px;
padding-top: 10px;
padding-right: 15px;
padding-bottom: 20px;
padding-left: 25px;
/* Shorthand */
padding: 10px 15px 20px 25px;
border: 1px solid black;
border-width: 2px;
border-style: dashed;
border-color: blue;
Width and Height
The width
and height
properties set the size of the content area of an element.
width: 200px;
height: 100px;
It's important to note that padding, border, and margin are not included in the width and height of an element by default. However, this behavior can be changed using the box-sizing
property.
Box Sizing: Content-box vs. Border-box
The box-sizing
property allows you to control how the width and height of an element are calculated.
box-sizing: content-box;
box-sizing: border-box;
Exercise: Creating a Card Layout
Now, let's put these concepts into practice by creating a simple card layout.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Card Layout</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="card">
<h2>Card Title</h2>
<p>This is a description of the card. It provides additional details and information.</p>
</div>
</body>
</html>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.card {
background-color: #fff;
padding: 20px;
margin: 10px;
border: 1px solid #ddd;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
width: 300px;
box-sizing: border-box;
}
.card h2 {
margin-top: 0;
}
.card p {
margin: 0;
}
Open the HTML file in a browser to see your styled card layout. Experiment with different margin, padding, and border values to see how they affect the layout.
Coming Up Next
In Chapter 4, we'll explore how to style text and fonts in CSS, including font families, sizes, and alignment, to enhance the typography of your web pages.
Please Sign In to post a comment.