Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 8 - Box Model

8.2 CSS Box Model Properties

In this lesson we will discuss some commonly used properties for styling elements with the CSS Box Model:

  1. Margin The margin property controls the space outside the border of an element. You can set margins individually for each side or use shorthand notation to set them all at once.

    div {
        margin-top: 20px;
        margin-right: 15px;
        margin-bottom: 20px;
        margin-left: 15px;
    }
    

    Shorthand notation:

    div {
        margin: 20px 15px 20px 15px;
    }
    
  2. Padding The padding property controls the space between the content and the border of an element. Similar to margins, you can specify padding individually for each side or use shorthand notation.

    div {
        padding-top: 20px;
        padding-right: 15px;
        padding-bottom: 20px;
        padding-left: 15px;
    }
    

    Shorthand notation:

    div {
        padding: 20px 15px 20px 15px;
    }
    
  3. Border The border property allows you to define the style, width, and color of the border around an element. You can set these properties individually for each side or use shorthand notation.

    div {
        border-width: 2px;
        border-style: solid;
        border-color: green;
    }
    

    Shorthand notation:

    div {
        border: 2px solid green;
    }
    
  4. Width and Height The width and height properties control the size of the content area of an element, excluding padding, borders, and margins.

    div {
        width: 200px;
        height: 100px;
    }
    

Example:

Let's combine these properties to create a styled element:

<!DOCTYPE html>
<html>
<head>
  <style>
    .box {
      width: 250px;
      height: 150px;
      padding: 20px;
      border: 5px solid green;
      margin: 30px;
      background-color: lightblue;
    }
  </style>
</head>
<body>
  <div class="box">This is a box with padding, border, and margin.</div>
</body>
</html>

In this example:

  • The .box class defines a box element with specific dimensions, padding, border, margin, and background color.
  • Adjustments to margin, padding, border, width, and height properties allow for precise control over the appearance and spacing of elements on the webpage.

Understanding and utilizing these properties effectively enables you to create visually appealing and well-structured layouts in CSS.