CSS Basic Selectors and Box Model
The box model allows us to add a border around elements, and to define space between elements. Width and Height of an Element To set the width and height of an element correctly in all browsers, you need to know how the box model works.
CSS Selectors
.class → Selects all elements with class=” intro”
.class1.class2 →Selects all elements with both name1 and name2 set within its class attribute
.class1 .class2 →Selects all elements with name2 that is a descendant of an element with name1(watch out for spaces)
#id →Selects the element with id=” first”.
*→ Selects all elements.
element → (for example: a) Selects all <a> elements
element.class → (for example : p.first) Selects all <p> elements with class=”first”
Box Model
Explanation of the different parts:
- Content — The content of the box, where text and images appear
- Padding — Clears an area around the content. The padding is transparent
- Border — A border that goes around the padding and content
- Margin — Clears an area outside the border. The margin is transparent
The box model allows us to add a border around elements, and to define space between elements.
Width and Height of an Element
To set the width and height of an element correctly in all browsers, you need to know how the box model works.
Important: When you set an element’s width and height properties with CSS, you just set the width and height of the content area. To calculate the full size of an element, you must also add padding, borders, and margins.
The total width of an element should be calculated like this:
Total element width = width + left padding + right padding + left border + right border + left margin + right margin
The total height of an element should be calculated like this:
Total element height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin
I took the Box model part from w3schools.com
“border-box” For Box Model
Why do we use border-box?
border-box tells the browser to account for any border and padding in the values you specify for an element’s width and height. If you set an element’s width to 100 pixels, that 100 pixels will include any border or padding you added, and the content box will shrink to absorb that extra width. ~MDN Web Docs
When we don’t use border-box