CSS Units
CSS has several different units for expressing a length. Many CSS properties take "length" values, such as width, margin, padding, font-size, etc.
1. Absolute Lengths
Absolute length units are fixed and a length expressed in any of these will appear as exactly that size. They are not recommended for use on screen, because screen sizes vary so much. However, they can be useful if the output medium is known, such as for print layout.
px(pixels): Relative to the viewing device. For low-dpi devices, 1px is one device pixel (dot) of the display. For printers and high resolution screens 1px implies multiple device pixels.cm: centimetersmm: millimetersin: inches (1in = 96px = 2.54cm)pt: points (1pt = 1/72 of 1in)pc: picas (1pc = 12 pt)
h1 { font-size: 24px; }
div { width: 5in; }
2. Relative Lengths
Relative length units specify a length relative to another length property. Relative units scale better between different rendering mediums.
em: Relative to the font-size of the element (2em means 2 times the size of the current font).rem: Relative to the font-size of the root element (usually<html>).%: Relative to the parent element.ch: Relative to the width of the "0" (zero) character.ex: Relative to the x-height of the current font (rarely used).
em vs rem
emcascades. If you nest elements withfont-size: 2em, the inner text grows exponentially.remis consistent. It always refers to the roothtmlfont size (default usually 16px).
html { font-size: 16px; }
.container {
font-size: 20px;
}
.child-em {
font-size: 2em; /* 2 * 20px = 40px */
}
.child-rem {
font-size: 2rem; /* 2 * 16px = 32px */
}
3. Viewport Units
Viewport units are relative to the size of the browser window (viewport).
vw(Viewport Width): 1% of the width of the viewport.vh(Viewport Height): 1% of the height of the viewport.vmin(Viewport Minimum): 1% of the smaller dimension (width or height).- If the viewport is 1000px wide and 800px high,
1vmin= 8px. - Useful for ensuring elements fit on screen regardless of orientation (portrait/landscape).
- If the viewport is 1000px wide and 800px high,
vmax(Viewport Maximum): 1% of the larger dimension (width or height).- If the viewport is 1000px wide and 800px high,
1vmax= 10px.
- If the viewport is 1000px wide and 800px high,
/* Full screen section */
.hero {
width: 100vw;
height: 100vh;
}
/* Responsive text */
h1 {
font-size: 5vmin; /* Scales with the smaller side, ensuring it fits */
}
4. Best Practices
- Use
remfor font sizes: This respects the user's browser settings and ensures accessibility. - Use
pxfor borders: Borders usually need to be crisp and thin. - Use
%or Flexbox/Grid for layout widths: Avoid fixed pixel widths for containers to ensure responsiveness. - Use
emfor padding/margins on components: This allows the spacing to scale if the component's font size changes.
programming/css/css programming/css/typography programming/css/responsive-design