CSS Height & Width
Controlling the height and width of elements helps define the structure of your page. By setting height
and width
, you can create consistent layouts, ensure images display correctly, and maintain a coherent design. You can use fixed units like pixels, or flexible units like percentages for responsive designs.
Key Topics
- Fixed Values
- Relative (Percentage) Values
- Max-Width, Min-Width, Max-Height, Min-Height
- Key Takeaways
Fixed Values
Setting width: 200px;
or height: 100px;
fixes an element’s size, ensuring consistency but not adapting to different screen sizes as easily.
Relative (Percentage) Values
Using percentages (e.g., width: 50%;
) makes elements scale based on their parent container, supporting responsive designs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Height & Width Example</title>
<style>
.box {
background-color: #ddd;
width: 50%;
height: 100px;
margin: 20px auto;
font-family: Arial, sans-serif;
text-align: center;
line-height: 100px;
}
</style>
</head>
<body>
<div class="box">This box is 50% width of its container and fixed 100px height.</div>
</body>
</html>
Explanation: The box’s width adapts to the container size, making the layout more flexible. However, its height remains fixed.
Max-Width, Min-Width, Max-Height, Min-Height
Use these properties to constrain elements. For example, max-width: 100%;
ensures images never overflow their container, while min-height: 200px;
guarantees enough vertical space.
Key Takeaways
- Control: Height and width define the shape and flow of elements.
- Responsive Design: Percentages and max/min properties enable flexibility across devices.
- Consistency: Fixed sizes ensure uniform layouts, but may be less adaptive.