Welcome back! We’re diving into the CSS Box-Model, a rite of passage for any web developer. Let’s see: "What's in the Box!?"
The Content Box
In web styling, everything is in a box. So far, we’ve only changed text sizes and colors. Now, we’ll explore positioning elements on a page with the CSS Box Model. It includes four parts: content, padding, border, and margin.
The content box tightly wraps your content, whether text, images, or other elements. For example, consider this example web page:
Here, the "Join the ride!" text is an <h1> element. The content box of that element looks like it wraps tightly around the text:
Notice the space around it? These spaces are controlled by the box model. Without it, everything would stack in the top left corner, like this:
The box model makes our pages interesting!
Padding, Border, and Margin
The rest of the box model:
Padding:
- Between the content box and the border
- Increases element size, combining with the content box for background properties
Border:
- The element’s edge, which can be styled
Margin:
- The space between elements, like an invisible pole pushing them apart
Moving Things Around
Understanding the box model is crucial for positioning elements. To save you some trial and error:
- To move the element: change its margins.
- To move the content inside the element: change its padding.
The Code
Let’s create our page:
<!DOCTYPE html>
<html>
  <head><!-- Metadata and linking --></head>
  <body>
    <h1>Join the ride!</h1>
    <p>A new model, each week!</p>
  </body>
</html>
h1 {
  /* Text Styles */
  margin: auto;
  margin-top: 60px;
  padding: 12px;
}
p {
  /* Text Styles */
  margin: auto;
  margin-top: 6px;
  padding: 3px;
}
Here’s the scoop:
- 
marginandpaddingcontrol spacing. They’re actually shorthand properties that include the propertiesmaring-top,margin-right,margin-bottom, andmargin-left. You can keep the same formatpadding's properties as well.
Using one property, we can set the padding size on all edges of the element:
p {
  padding: 12px 50px 100px 2px; /* top right bottom left */
}
Or we can set the top/bottom and the left/right to be symmetrical by setting only two values:
p {
  padding: 12px 50px; /* top/bottom left/right */
}
Or set all the sides the same, by using one:
p {
  padding: 12px; /* all sides */
}
Both padding and margin can use distance values (px, em) or percentages (%). The auto keyword is also handy in conjunction with margin for centering elements!
Challenge
Time to test your skills!
- Put four elements on a web page. Keep them roughly the same size.
- Add borders around them (check MDN for border styling).
- Center one element.
- Make another element’s border larger than its content.
You’ve got the tools—now go position your elements like a pro!
For a much more robust look at the box model, check out MDN's Documentation!
 
 
              





 
    
Top comments (0)