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
Define the width of each column in CSS Grid Layout
The CSS grid-template-columns property is used to define the width of each column in a CSS Grid Layout. You can specify different widths for each column using various units like pixels, percentages, or fractional units.
Syntax
.grid-container {
display: grid;
grid-template-columns: value1 value2 value3 ...;
}
Possible Values
| Value | Description |
|---|---|
px |
Fixed width in pixels |
% |
Percentage of container width |
fr |
Fractional unit for flexible sizing |
auto |
Automatically sized based on content |
Example: Fixed Column Widths
The following example creates a grid with three columns having fixed widths of 120px, 80px, and 50px respectively −
<!DOCTYPE html>
<html>
<head>
<style>
.container {
display: grid;
background-color: #f0f0f0;
grid-template-columns: 120px 80px 50px;
padding: 20px;
gap: 15px;
}
.container > div {
background-color: #4CAF50;
color: white;
border: 2px solid #333;
padding: 20px;
font-size: 18px;
text-align: center;
border-radius: 5px;
}
</style>
</head>
<body>
<h2>Grid with Fixed Column Widths</h2>
<div class="container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
</body>
</html>
A grid layout with three columns appears. The first column is 120px wide, the second is 80px wide, and the third is 50px wide. Six green boxes with numbers 1-6 are arranged in two rows across these three columns.
Example: Flexible Column Widths Using Fractional Units
You can also use fractional units (fr) to create flexible columns that share available space proportionally −
<!DOCTYPE html>
<html>
<head>
<style>
.flexible-container {
display: grid;
background-color: #e8f4fd;
grid-template-columns: 1fr 2fr 1fr;
padding: 20px;
gap: 15px;
margin-top: 20px;
}
.flexible-container > div {
background-color: #2196F3;
color: white;
padding: 20px;
text-align: center;
border-radius: 5px;
}
</style>
</head>
<body>
<h2>Grid with Flexible Column Widths</h2>
<div class="flexible-container">
<div>Column 1</div>
<div>Column 2 (2x wider)</div>
<div>Column 3</div>
</div>
</body>
</html>
A flexible grid layout with three columns appears. The middle column is twice as wide as the first and third columns. The columns automatically adjust to fill the available container width proportionally.
Conclusion
The grid-template-columns property provides powerful control over column widths in CSS Grid. Use fixed units for precise control or fractional units for responsive, flexible layouts that adapt to container size.
Advertisements
