CSS provides various units for defining sizes, lengths, and dimensions. These units can be relative or absolute and each serves different purposes in layout and design.
Below are examples of different CSS units used for sizing elements:
.pixels {
background-color: #f00;
width: 100px;
height: 100px;
}
.percent {
background-color: #0f0;
width: 50%;
height: 100px;
}
.em {
background-color: #00f;
width: 10em;
height: 10em;
}
.rem {
background-color: #ff0;
width: 10rem;
height: 10rem;
}
.vh {
background-color: #f0f;
width: 50vw;
height: 50vh;
}
.vw {
background-color: #0ff;
width: 50vw;
height: 50vw;
}
.ch {
background-color: #ff6;
width: 20ch;
height: 5em;
}
.vmin {
background-color: #0f6;
width: 20vmin;
height: 20vmin;
}
.vmax {
background-color: #6f0;
width: 20vmax;
height: 20vmax;
}
Width and height are set using pixels (px).
Width is set to 50% of the parent element.
Width and height are set using ems (relative to font-size).
Width and height are set using rems (relative to root font-size).
Width is set to 50% of the viewport width and height to 50% of viewport height.
Width and height are set relative to viewport width.
Width is set relative to the width of the "0" character in the current font.
Width and height are set to 20% of the viewport's smaller dimension.
Width and height are set to 20% of the viewport's larger dimension.