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
Usage of width property with CSS
The width property in CSS is used to set the width of elements, including images. This property accepts values in various units such as pixels (px), percentages (%), em, rem, and other CSS length units. When using percentage values, the width is calculated relative to the containing element's width.
Syntax
width: value;
Common Values
-
Pixels (px): Absolute unit -
width: 200px; -
Percentage (%): Relative to parent container -
width: 50%; -
Auto: Browser calculates width automatically -
width: auto; -
Em/Rem: Relative to font size -
width: 10em;
Example: Setting Image Width
Here's how to set different width values for images:
<html>
<head>
<style>
.container {
border: 1px solid #ccc;
padding: 10px;
width: 300px;
}
.fixed-width {
border: 2px solid green;
width: 100px;
}
.percentage-width {
border: 2px solid blue;
width: 50%;
}
.responsive-width {
border: 2px solid red;
width: 100%;
max-width: 150px;
}
</style>
</head>
<body>
<div class="container">
<h3>Fixed Width (100px)</h3>
<img class="fixed-width" src="/css/images/logo.png" alt="Fixed width image" />
<h3>Percentage Width (50%)</h3>
<img class="percentage-width" src="/css/images/logo.png" alt="Percentage width image" />
<h3>Responsive Width (100% with max-width)</h3>
<img class="responsive-width" src="/css/images/logo.png" alt="Responsive width image" />
</div>
</body>
</html>
Width Units Comparison
| Unit | Description | Use Case |
|---|---|---|
| px | Absolute pixels | Fixed layouts, precise control |
| % | Relative to parent | Responsive designs, fluid layouts |
| auto | Browser calculated | Default sizing, natural dimensions |
| em/rem | Relative to font size | Scalable components |
Key Points
- Percentage values are calculated relative to the parent container's width
- Use
max-widthwith percentage values to prevent oversized elements - The
widthproperty affects the content area, not including padding, border, or margin - Images maintain aspect ratio by default when only width is specified
Conclusion
The CSS width property provides flexible control over element sizing. Use pixels for fixed layouts and percentages for responsive designs that adapt to different screen sizes.
Advertisements
