The CSS box model is a fundamental concept in web development that describes the layout and spacing of elements. Here’s a cheat sheet covering key aspects of the CSS box model:
Content Box
- Width and Height:
width
: Width of the content box.height
: Height of the content box.
- Padding:
padding
: Space between the content and the border.padding-top
,padding-right
,padding-bottom
,padding-left
: Individual padding values.
- Border:
border
: Combination of border-width, border-style, and border-color.border-width
: Width of the border.border-style
: Style of the border (e.g., solid, dashed).border-color
: Color of the border.
- Margin:
margin
: Space outside the border, creating the outer spacing.margin-top
,margin-right
,margin-bottom
,margin-left
: Individual margin values.
Box Sizing
- box-sizing:
content-box
(default): Width and height include only the content.border-box
: Width and height include content, padding, and border.
- Calculating Total Width:
width: width + padding + border;
Display Property
- display:
block
: Element takes up full width, starts on a new line.inline
: Element takes only as much width as necessary, does not start on a new line.inline-block
: Element is inline but can have a width and height.
- Visibility:
visibility: hidden
: Hides the element but still takes up space.display: none
: Hides the element and removes it from the layout.
Overflow
- overflow:
visible
(default): Content overflows the box.hidden
: Content is clipped, and the overflow is hidden.scroll
: Adds a scrollbar when content overflows.
Responsive Box Model
- max-width and max-height:
- Restricts the maximum width and height of an element.
- min-width and min-height:
- Specifies the minimum width and height for an element.
Centering Elements
Centering Horizontally:
margin-left: auto;
margin-right: auto;
Centering Vertically:
display: flex;
align-items: center;
justify-content: center;
Practical Tips
Box Model Reset:
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
Border Box for All Elements:
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
Clearfix:
- Prevents collapsing of parent element’s height when children are floated.
.clearfix::after {
content: "";
display: table;
clear: both;
}
This cheat sheet provides a quick reference for understanding and working with the CSS box model. Adjust the values and properties based on your specific layout requirements.