P粉2949544472023-08-31 11:33:30
The width of the image column is not arbitrary.
The grid container lays out the structure first. . Then is arranging items.
This means that the first column will resize when the image is at its natural width (100%).
The browser does not go back and resize the column when the item is rendered with width: 50%
.
So the size of the columns is not arbitrary; it is the natural width of the image.
(This is arguably a bug or CSS limitation.)
Please note that this problem does not exist when the image is full width:
* { box-sizing: border-box; } body { margin: 0; } header { display: grid; grid-template-columns: auto 1fr; background-color: green; padding: 1rem; } img { width: 100%; background-color: pink; } div { background-color: red; } nav { background-color: yellow; grid-column: span 2; }
<header> <div style="background-color: blue"> <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 324 413.28'%3E%3Crect class='655de5e2-44d3-4b5a-ae63-e6e7ec799246' x='18' y='18.12' width='288' height='324' fill='blue'/%3E%3C/svg%3E"> </div> <div> <h1>Heading</h1> <p>Text Line 1</p> <p>Text Line 2</p> <p>Text Line 3</p> </div> <nav> <a href="#">Menu Item 1</a> <a href="#">Menu Item 2</a> <a href="#">Menu Item 3</a> <a href="#">Menu Item 4</a> <a href="#">Menu Item 5</a> <a href="#">Menu Item 6</a> </nav> </header>
When you try width: 150%
it will come back:
* { box-sizing: border-box; } body { margin: 0; } header { display: grid; grid-template-columns: auto 1fr; background-color: green; padding: 1rem; } img { width: 150%; background-color: pink; } div { background-color: red; } nav { background-color: yellow; grid-column: span 2; }
<header> <div style="background-color: blue"> <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 324 413.28'%3E%3Crect class='655de5e2-44d3-4b5a-ae63-e6e7ec799246' x='18' y='18.12' width='288' height='324' fill='blue'/%3E%3C/svg%3E"> </div> <div> <h1>Heading</h1> <p>Text Line 1</p> <p>Text Line 2</p> <p>Text Line 3</p> </div> <nav> <a href="#">Menu Item 1</a> <a href="#">Menu Item 2</a> <a href="#">Menu Item 3</a> <a href="#">Menu Item 4</a> <a href="#">Menu Item 5</a> <a href="#">Menu Item 6</a> </nav> </header>
Side note
In general, when using CSS Grid and Flexbox, it is not a good idea to make images as children of containers.
In other words, it's generally best to avoid using images as grid or flex items.
There are too many bugs and rendering differences between different browsers.
In many cases, simply placing the image inside a div
(making the div
a grid item) will solve the problem.
Avoid using images as grid or flex items: