CSS Borders, Margins, and Padding

Hey friends 👋 welcome back. In the last tutorial, we explored colors and text styling. Today, we’re going to talk about something very important in web design — borders, margins, and padding. These three things control the spacing and structure of your web pages.

Think of them like this:

  • Content → the actual text or image.

  • Padding → the space between the content and the border.

  • Border → the line that surrounds the element.

  • Margin → the space outside the border, separating the element from others.

This is often called the box model in CSS.



Borders

Borders are lines that surround an element. You can control their width, style, and color.

Example:

<!DOCTYPE html> <html> <head> <title>CSS Borders</title> <style> p { border: 2px solid blue; } h1 { border: 3px dashed red; } </style> </head> <body> <h1>This heading has a red dashed border</h1> <p>This paragraph has a blue solid border.</p> </body> </html>

Border styles include: solid, dashed, dotted, double, groove, ridge, inset, and outset.

Padding

Padding is the space inside the border — it pushes the content away from the edges.

Example:

<!DOCTYPE html> <html> <head> <title>CSS Padding</title> <style> p { border: 2px solid green; padding: 20px; } </style> </head> <body> <p>This paragraph has 20px padding inside the border.</p> </body> </html>

You can set padding for each side:

padding-top: 10px; padding-right: 15px; padding-bottom: 10px; padding-left: 15px;

Or shorthand:

padding: 10px 15px 10px 15px;

Margins

Margins create space outside the border, pushing elements away from each other.

Example:

<!DOCTYPE html> <html> <head> <title>CSS Margins</title> <style> h1 { border: 2px solid purple; margin: 50px; } </style> </head> <body> <h1>This heading has 50px margin around it</h1> <p>This paragraph is not affected.</p> </body> </html>

Just like padding, you can set margins for each side:

margin-top: 20px; margin-right: 30px; margin-bottom: 20px; margin-left: 30px;

Or shorthand:

margin: 20px 30px 20px 30px;

The Box Model

Borders, padding, and margins together create the box model, which controls how every element is spaced and sized on a page. Understanding this is one of the most important steps to becoming good at CSS.

Try It Yourself

Create a new file called boxmodel.html. Inside it, write a heading and a paragraph. Add a border to both, give them some padding, and use margins to separate them from each other. Experiment with different numbers like 10px, 20px, or 50px and see how it changes the layout.

Great job 🎉 You just learned about borders, margins, and padding in CSS. In the next tutorial, we’ll move on to CSS Backgrounds — where we’ll learn how to use background colors, gradients, and even images to make our websites stand out. 🚀