在解决这个问题一段时间后,我认为这不是网格布局的问题。
由于您从未为 SVG 定义 height/max-height 或 width/max-width,因此计算的是 width:auto 和 height:auto p>
注意:我提出 max-height/max-width,因为这些值优先于 width/height 值。 p>
那么,为什么您的 landscape 布局有效而您的 portrait 布局无效?
因为宽度比身高“优先”。
这就是为什么在块布局中,自动高度基于后代的总高度,而自动宽度基于包含块的宽度。
Source - Why does width:auto behave differently than height:auto?
这意味着您的 SVG 正在从其容器中获取 width 并从其后代中获取 height。
在您的示例中,您的 SVG 没有后代,但有一个定义了 max-width 的父级。
但这对 SVG 的高度意味着什么?
SVG 正在通过内在比率计算它的高度:
如果“svg”元素上的“viewBox”被正确指定:
- 让 viewbox 成为由“svg”元素上的“viewBox”属性定义的视图框
- 返回 viewbox.width / viewbox.height
Source
而你的内在比率是1/1 = 1
所以你强迫你的height=width
解决方案
解决方案是根据父 div 的比例为 SVG 设置 width 或 margin。
在您给出的示例中,您的比例为 2:1,因此您的 SVG 应该有 width:50% 或 margin: 0 25%。
这意味着如果要设置不同的比例,则必须进行相应的调整(参见下面代码中的 Portrait-1-3)。
如果height 不是约束,则可以避免为每个比例设置 CSS 规则,因为您可以为 SVG 和容器定义 width,让元素调整 height 以保持纵横比。
如果有人不关心保持纵横比但需要将 SVG 包含在一组 height 和 width 容器中,我还添加了最后一个示例。
.container {
display: grid;
background-color: greenyellow;
margin: 5px;
min-height: 10px;
min-width: 10px;
}
.portrait {
max-height: 100px;
max-width: 200px;
}
/* Add 25% margin left and right to center the image OR set the image width to 50% */
.portrait>.aspect-ratio {
margin: 0 25%;
/*
or
width:50%;
*/
}
.landscape {
max-height: 200px;
max-width: 100px;
}
.aspect-ratio {
grid-column: 1;
grid-row: 1;
background-color: deeppink;
border-radius: 50%;
align-self: center;
justify-self: center;
}
/* Set fixed max-height and max-width rule (33% proportion) */
.portrait-1-3 {
max-height: 100px;
max-width: 300px;
}
/* Align image with the new proportion */
.portrait-1-3>.aspect-ratio {
margin: 0 33.33%;
/*
or
width:33.3%;
*/
}
/* Removed max-height and let the container adjust the height according to the max-width rule and the proportion set */
.portrait-any-height {
max-width: 400px;
}
/* Height will be adjusted through the width/margin defined here, so 10% width will correspond to 40px of height (10%*400px)*(aspect ratio=1)*/
.portrait-any-height>.aspect-ratio {
width:10%;
}
/* Set fixed max-height and max-width rule (proportion doesn't matter) */
.portrait-squeezed {
max-height: 100px;
max-width: 300px;
}
/* Make sure SVG complies with the the given max with and height (squeezing your svg) */
.portrait-squeezed>.aspect-ratio {
max-height: inherit;
max-width: inherit;
}
<div class="container landscape">
<svg class="aspect-ratio" viewBox="0 0 1 1"></svg>
</div>
<div class="container portrait">
<svg class="aspect-ratio" viewBox="0 0 1 1"></svg>
</div>
<div class="container portrait-1-3">
<svg class="aspect-ratio" viewBox="0 0 1 1"></svg>
</div>
<div class="container portrait-any-height">
<svg class="aspect-ratio" viewBox="0 0 1 1"></svg>
</div>
<div class="container portrait-squeezed">
<svg class="aspect-ratio" viewBox="0 0 1 1"></svg>
</div>
请注意,我对 SVG 的使用不是很熟练,这个回复是研究和大量实验的结果!
我很乐意收到对我的回复的任何调整和/或更正。