Reputation: 12598
I am using CSS grid to create a simple 3 column layout like this...
.container {
display:grid;
grid-template-columns:1fr 1fr 1fr;
}
.col1 {
background:red;
text-align:center;
}
.col2 {
background:yellow;
text-align:center;
}
.col3 {
text-align:center;
background:green;
}
<div class="container">
<div class="col1">
Column 1
</div>
<div class="col2">
<img src="https://via.placeholder.com/150">
</div>
<div class="col3">
Column 3
</div>
</div>
I am trying to change things so that the center div is only as wide as the image it contains, then col1
and col2
stretch to fill the remaining space.
Anyone have an example they can show me?
Upvotes: 4
Views: 6903
Reputation: 346
Try below snippet.
.container {
display:grid;
grid-template-columns:1fr auto 1fr;
}
.col1 {
background:red;
text-align:center;
}
.col2 {
background:yellow;
text-align:center;
}
.col3 {
text-align:center;
background:green;
}
<div class="container">
<div class="col1">
Column 1
</div>
<div class="col2">
<img width="300px" height="300px" src="https://via.placeholder.com/150">
</div>
<div class="col3">
Column 3
</div>
</div>
Upvotes: -1
Reputation: 363
grid-template-columns:1fr auto 1fr;
Here you go, use the auto
instead of 1fr
for the centered div.
Upvotes: 0
Reputation: 42352
Change grid-template-columns
to 1fr auto 1fr
- see demo below:
.container {
display: grid;
grid-template-columns: 1fr auto 1fr;
/* changed */
}
.col1 {
background: red;
text-align: center;
}
.col2 {
background: yellow;
text-align: center;
}
.col3 {
text-align: center;
background: green;
}
img {
display: block; /* remove inline element "space" below image */
}
<div class="container">
<div class="col1">
Column 1
</div>
<div class="col2">
<img src="https://via.placeholder.com/150">
</div>
<div class="col3">
Column 3
</div>
</div>
Upvotes: 4