Unable to create responsive grid area using svg image
P粉0221405762023-08-30 19:15:16
0
1
552
<p>When I try to create a responsive grid area containing an svg image, I encounter strange behavior, such as arbitrary grid area widths, and an inability to get the image to grow or shrink to a certain point without stopping. The closest I got was: </p>
<p>
<pre class="brush:css;toolbar:false;">* {
box-sizing: border-box;
}
body {
margin: 0;
}
header {
display: grid;
grid-template-columns: auto 1fr;
background-color: green;
padding: 1rem;
}
img {
width: 100%;
max-width: 25vw;
min-width: 12rem;
background-color: pink;
}
div {
background-color: red;
text-align: center;
}
nav {
background-color: yellow;
grid-column: span 2;
}</pre>
<pre class="brush:html;toolbar:false;"><header>
<img src="data:image/svg xml,">
<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></pre>
</p>
<p>I've tried height, min-height, max-height, and even using clips within the width with little success. Maybe I just lack understanding, like some of the existing replies suggest, but don't know how to fix it. </p>
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:
When you try
width: 150%
it will come back: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 thediv
a grid item) will solve the problem.Avoid using images as grid or flex items: