Percentages (%) provide a flexible way to define sizes relative to the size of their parent element. This makes layouts adaptable to different screen sizes and resolutions.
Usage
Font sizes
- Set font sizes relative to the parent element’s font size:
p {
font-size: 120%; /* 120% of the parent's font size */
}
Dimensions (width, height, padding, margin)
- Define dimensions relative to the parent element’s width or height:
div {
width: 80%; /* 80% of the parent's width */
height: 50%; /* 50% of the parent's height */
padding: 10%; /* 10% padding around the content */
margin: 20%; /* 20% margin around the element */
}
Line heights
- Set line heights relative to the font size:
p {
line-height: 150%; /* 150% of the font size */
}
Key points
- Relative to parent: Percentages are always calculated based on the size of the parent element, not the entire document.
- Nested elements: Percentages in nested elements are calculated relative to their immediate parent’s size.
- Viewport units: For dimensions relative to the viewport (browser window), use viewport units like
vw(viewport width) andvh(viewport height).
Example
<div style="width: 800px; height: 600px;">
<div style="width: 50%; height: 50%; background-color: lightblue;"></div>
<div style="width: 30%; height: 30%; background-color: lightgreen;"></div>
</div>
In this example, the two inner divs will have widths and heights of 400px and 300px, respectively, because they are 50% and 30% of their parent’s dimensions.
Additional notes
- Browser compatibility: Percentages are widely supported across modern browsers.
- Accessibility: Ensure that using percentages doesn’t negatively impact accessibility. Consider using a minimum font size or other techniques to maintain readability.