Understand how every element is a box made of content, padding, border and margin, and master box-sizing.
Open this lesson in KodokonIn CSS, every element on the page is a rectangular box, even if you cannot see it. That box has four layers, like a framed painting hanging on a wall: the content (the picture itself), the padding (the white matting between the picture and the frame), the border (the frame itself) and the margin (the empty space between the frame and the other paintings on the wall). This is what we call the box model.
Three properties control these layers. padding sets the inner space, between the content and the border. border draws the border: you give it a thickness, a style (solid for a solid line) and a color. margin sets the outer space, which pushes neighboring elements away. All these distances are expressed in pixels (px).
.card {
padding: 16px;
border: 2px solid black;
margin: 24px;
}You can adjust each side separately with padding-top, padding-right, padding-bottom and padding-left, and the same goes for margin. There are also shorthands: with two values, the first applies to the top and bottom, the second to the left and right. So padding: 8px 16px; means 8 pixels on the top and bottom, 16 pixels on the left and right.
.card {
padding: 8px 16px;
margin-top: 32px;
margin-bottom: 8px;
}A classic pitfall: by default, when you write width: 200px; (the width property sets the width), those 200 pixels cover the content only. The padding and the border are added on top! A box with width: 200px, padding: 16px and border: 2px actually takes up 200 + 16 + 16 + 2 + 2 = 236 pixels of width. The box-sizing: border-box; property fixes this: the declared width then includes the padding and the border. The box is truly 200 pixels wide, and it is the content that shrinks.
* {
box-sizing: border-box;
}
.card {
width: 200px;
padding: 16px;
border: 2px solid black;
}box-sizing: border-box, what total width does a box with width: 100px, padding: 10px and border: 5px solid black take up?margin: 10px 20px; mean?