Box Sizing

Exercise

  1. In the "index.html" file, replace the code with the following:
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CSS</title>
  <link rel="stylesheet" href="./css/styles.css">
</head>

<body>
  <h1>Box-sizing</h1>
  <div id="content-box">
    <p>This is the default box-sizing of content-box</p>
  </div>
  <div id="no-box-sizing">
    <p>This has no box-sizing property and is the same as the previous example</p>
  </div>
  <div id="border-box">
    <p>This is box-sizing of border-box</p>
  </div>
</body>

</html>
  1. Save.
  2. If "Live Server" is not already running, right-click anywhere in the editor and select "Open with Live Server" from the context menu.
  3. In the "styles.css" file, replace the code with the following:
p {
  color: white;
}

div {
  width: 150px;
  height: 150px;
}

#content-box {
  background-color: blue;
  box-sizing: content-box;
  padding: 10px;
}

#no-box-sizing {
  background-color: red;
  padding: 10px;
}

#border-box {
  background-color: green;
  box-sizing: border-box;
  padding: 10px;
}
  1. Save.
  2. In the browser, you should see the following:

  3. Exercise 2 Result

Code Walkthrough and Explanation


box-sizing

box-sizing is a CSS property that determines how the size of an element is calculated. By default, the size of an element is calculated based on its content, padding, and border, but with box-sizing, you can change this behavior to include or exclude the element's padding and border from the calculation.

There are two values for the box-sizing property:

box-sizing is a useful property because it helps ensure consistent sizing and layout of elements in your web page.


Experiment with the Code


Video and Code References


Questions? Subscribe and ask in the video comments:




GitHub and Other References