16. Setting Width and Height (Fixed vs. Fluid)
We define the dimensional limits of an element using width, height, and their related min/max counterparts.
Fixed Dimensions (Pixels)
Using units like px defines a fixed size. The element will always be that size, regardless of the screen size or its parent container.
css .fixed-sidebar { width: 300px; /* Always 300 pixels wide / height: 800px; / Always 800 pixels tall */ }
Fixed dimensions are good for elements that shouldn't change size (like logos or standard icons).
Fluid Dimensions (Percentages and Viewport Units)
Using percentages (%) or viewport units (vw, vh) creates fluid elements that adapt to their container or the screen size.
1. Percentages (%)
width: 50%means the element will take up 50% of the width of its immediate parent element.heightpercentages are often unreliable unless the parent element has a defined height.
css .half-width { width: 50%; /* 50% of the parent container's width */ }
2. Minimum and Maximum Constraints
These are essential for responsive design. They prevent elements from getting too small or too large.
| Property | Description |
|---|---|
min-width | Element cannot shrink below this value. |
max-width | Element cannot grow beyond this value (Very common: max-width: 100% is often used on images). |
min-height | Element cannot shrink below this height. |
max-height | Element cannot grow above this height. |
css .main-content { width: 90%; max-width: 1200px; /* Never wider than 1200px / min-height: 400px; / Always at least 400px tall */ }