Learn CSS Box Model




The image below demonstrates the CSS Box model:

css box model

The CSS Model box is a rectangle consists of elements, such as padding, margin, width, height, and ofcourse the content.


Understanding the CSS Model box will help you control your website style and quickly understand other web developers CSS code.


The height and the width inside the CSS Model box define the height and width of an HTML Element, the Border defines the border around the padding and content, the padding clears an area around the content, padding is transparent, the margin affect how other content properties interacting with the CSS Model box.


The margin is unique in that it doesn't affect the size of the box itself.


When opening a web page, the browser's rendering engine represents each element as a rectangular box (The model box).


Understanding the CSS Model box is helpful, when using the developer tool (click F12 on chrome browser to open it)


Code Example:


            <style>
      div {
  width: 250px;
  padding: 60px;
  margin: 25px;
  border: 20px solid blue;
}
</style>

 
  
Try yourself >>






CSS Model box Padding


The CSS padding property define the padding area of an HTML Element, the default padding value is zero.


CSS padding has four sub properties:


  • padding-bottom
  • padding-top
  • padding-right
  • padding-left

Check out the next code example to see the diffrence between the two CSS Model boxes when using diffrenet padding values:


Code Example:


            <style>
      .box-1 {
  width: 250px;
  padding: 30px;
  margin: 25px;
  border: 20px solid blue;
}
.box-2 {
  width: 250px;
  padding: 120px;
  margin: 25px;
  border: 20px solid blue;
}
</style>

 
  
Try yourself >>







CSS Model box Width and Height


When we create the height and width of an HTML element, we are not creating the full size of the element, but the content area, we should also add borders, margin and padding, the total width of the element in the example is 430 pixels:



Code Example:


            <style>
    div {
      padding: 10px;
  width: 400px;
  border: 5px solid blue;
  margin: 0;
}
</style>

 
  
Try yourself >>



This is the calculation the browser does:


400 pixels (width) + 20 pixels (left + right padding) + 10 pixels (left + right border) + 0 pixels (left + right margin) = 430 pixels








learn css basics in 1 day, you are in the right place to learn css full tutorial, FreeCodeWiki is one of the best websites that teach css3 tutorial for beginners



Navigation