CSS units are used to measure various elements and their properties in a web page. They define the size, spacing, and layout of elements.
Absolute Units
Absolute units are fixed and not relative to any other element. They are always the same size, regardless of other settings.
- cm (centimeters): 1cm = 37.8px
- mm (millimeters): 1mm = 1/10th of a cm = 3.78px
- in (inches): 1in = 2.54cm = 96px
- px (pixels): 1px = 1/96th of an inch
- pt (points): 1pt = 1/72nd of an inch = 1.333px
- pc (picas): 1pc = 12 points = 16px
Relative Units
Relative units are relative to other measurements. They adapt based on the context, making them more flexible.
- em: Relative to the font-size of the element. If the font-size of the element is 16px, 1em is 16px.
- rem: Relative to the font-size of the root element (usually the <html> element). If the root element font-size is 16px, 1rem is 16px.
- %: Relative to the parent element’s property. 50% width means half the width of the parent element.
- vw (viewport width): 1vw = 1% of the viewport's width.
- vh (viewport height): 1vh = 1% of the viewport's height.
- vmin: 1vmin = 1% of the smaller dimension of the viewport (height or width).
- vmax: 1vmax = 1% of the larger dimension of the viewport (height or width).
Max-Width
.element {
max-width: 600px;
}
- If the content of the element is wider than the max-width, it will shrink to fit within the max-width.
- If the content is smaller, it will not stretch to meet the max-width.
Min-Width
.element {
min-width: 300px;
}
- If the content of the element is narrower than the min-width, it will expand to meet the min-width.
- If the content is wider, it will not shrink below the min-width.
Usage Examples
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Units</title>
<style>
.box-absolute {
width: 100px; /* Absolute unit: pixels */
height: 5cm; /* Absolute unit: centimeters */
background-color: lightblue;
}
.box-relative {
width: 50%; /* Relative unit: percentage of parent element */
height: 10vh; /* Relative unit: 10% of viewport height */
background-color: lightcoral;
}
.box-max-width {
width: 100%; /* Start with full width */
max-width: 500px; /* Restrict maximum width */
background-color: lightgreen;
}
.box-min-width {
width: 50%; /* Start with 50% width */
min-width: 200px; /* Ensure minimum width */
background-color: lightgoldenrodyellow;
}
</style>
</head>
<body>
<div class="box-absolute">Absolute Units</div>
<div class="box-relative">Relative Units</div>
<div class="box-max-width">Max-Width Example</div>
<div class="box-min-width">Min-Width Example</div>
</body>
</html>
No comments:
Post a Comment