CSS

Last Updated: 10/18/2022

Box Model

  • All HTML elements can be considered as boxes.
  • It consists of margins, borders, padding, and the actual content.
  • Content: The content of the box, where text and images appear
  • Padding: Space between content and border
  • Border - A border that goes around the padding and content
  • Margin - Space between elements
p {
	margin: 10px;
	padding: 20px;
	border: 5px solid blue;
}

Padding

  • Padding is used to create space around an element's content, inside of any defined borders.
p {
	padding-top: 10px;
	padding-right: 20px;
	padding-bottom: 30px;
	padding-left: 40px;
}

Shorthand

p {
	padding: 10px 20px 30px 40px;
}

Same values on all sides

p {
	padding: 10px;
}

Margin

  • Margins are used to create space around elements, outside of any defined borders.
p {
	margin-top: 10px;
	margin-right: 20px;
	margin-bottom: 30px;
	margin-left: 40px;
}

Shorthand

p {
	margin: 10px 20px 30px 40px;
}

Same values on all sides

p {
	margin: 10px;
}

Margin auto

  • You can set the margin property to auto to horizontally center the element within its container.
  • The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.
div {
	width: 500px;
	margin: auto;
	border: 5px solid blue;
}

Margin Collapse

  • Top and bottom margins of elements are sometimes collapsed into a single margin that is equal to the largest of the two margins.
  • This does not happen on left and right margins! Only top and bottom margins!
p {
	margin: 10px 0px 30px 0px;
}

Box Sizing

  • Possible values are content-box, border-box

Content-box

  • Default is content-box
#p1 {
	width: 200px;
	height: 200px;
	border: 1px solid green;
}
#p2 {
	width: 200px;
	height: 200px;
	padding: 10px;
	border: 5px solid green;
}

width + horizontal padding + horizontal border = actual width of an element height + vertical padding + vertical border = actual height of an element

Border-box

  • Allows us to include the padding and border in an element's total width and height.
#p1 {
	width: 200px;
	height: 200px;
	border: 1px solid green;
	box-sizing: border-box;
}
#p2 {
	width: 200px;
	height: 200px;
	padding: 10px;
	border: 5px solid green;
	box-sizing: border-box;
}