Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
The width and height properties in CSS
The CSS width and height properties define the dimensions of an element's content area, excluding margins, padding, and borders. These fundamental properties give you precise control over element sizing.
Syntax
selector {
width: value;
height: value;
}
Possible Values
| Value | Description |
|---|---|
auto |
Browser calculates dimensions automatically (default) |
length |
Fixed size in px, em, rem, etc. |
% |
Percentage of parent element's dimensions |
initial |
Sets to default value |
inherit |
Inherits from parent element |
Example: Fixed Dimensions
The following example demonstrates setting specific width and height values −
<!DOCTYPE html>
<html>
<head>
<style>
.container {
width: 70%;
margin: 0 auto;
padding: 20px;
background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
text-align: center;
border-radius: 10px;
}
.box1 {
background-color: #fff;
padding: 10px;
margin: 10px 0;
border-radius: 5px;
}
.box2 {
width: 200px;
height: 100px;
background-color: #f39c12;
color: white;
display: flex;
align-items: center;
justify-content: center;
margin: 10px auto;
border-radius: 5px;
}
</style>
</head>
<body>
<div class="container">
<div class="box1">
This box has automatic dimensions
</div>
<div class="box2">
200px × 100px
</div>
</div>
</body>
</html>
A centered container with gradient background containing two boxes: one with automatic sizing and another fixed at 200px wide by 100px tall with orange background and white text.
Example: Auto Height
When height is set to auto, the browser calculates it automatically based on content −
<!DOCTYPE html>
<html>
<head>
<style>
.pagination {
display: inline-block;
background-color: #333;
border-radius: 8px;
height: auto;
overflow: hidden;
}
.page-link {
display: inline-block;
padding: 12px 16px;
color: #fff;
text-decoration: none;
transition: background-color 0.3s;
}
.page-link:hover {
background-color: #555;
}
.page-link.active {
background-color: #007bff;
}
</style>
</head>
<body>
<h2>Auto Height Example</h2>
<div class="pagination">
<a class="page-link" href="#">«</a>
<a class="page-link active" href="#">1</a>
<a class="page-link" href="#">2</a>
<a class="page-link" href="#">3</a>
<a class="page-link" href="#">»</a>
</div>
</body>
</html>
A dark pagination component with auto height that adjusts to fit the link content. The height automatically adapts to the padding and font size of the navigation links.
Conclusion
The width and height properties are essential for controlling element dimensions. Use fixed values for precise control or auto for flexible, content-based sizing.
Advertisements
