我正在寻找将svg
国旗放在圆形div
容器中的 CSS 解决方案。
为此,我的计划是将容器设置为height
等于width
和border-radius: 100%;
,使其变成一个圆圈,然后设置隐藏孩子溢出圆圈overflow: hidden;
的任何部分。svg
缺少的一点是我应该将孩子svg
与父母水平居中。我怎样才能做到这一点?弹性盒或网格布局可能是要走的路吗?
如果它很重要,我计划让圆圈成为一个可点击的元素(其中会有几个,并且它们的行为就像替代单选按钮一样,功能上)。
一些我无法适应我的案例的相关问题/答案:
- 当子元素大于父元素时,如何将子元素置于父元素上方/下方居中(加上旋转)?
- CSS - 将子 div 拉伸到其溢出的父级的完整高度
- 如何在流体布局中垂直居中父 div 内的子 div 内容
- 如何在 CSS 中将子元素居中,即使它大于父元素?
(两者也应该垂直居中,但由于标志通常比它们高,容器和图像可以共享相同的height
,例如孩子可以设置height: inherit;
。)
.country-flag {
height: 3em;
width: 3em;
border-radius: 100%;
position: relative;
overflow: hidden;
}
.country-flag > svg {
width: auto;
height: 3em;
position: absolute;
left: -27%; /* but this is not accurate! Ideally it is `-1 * (width - height)/2` */
}
<div class="country-flag">
<svg xmlns="http://www.w3.org/2000/svg" width="1500" height="1000" viewBox="0 0 3 2">
<rect width="3" height="2" fill="#009246"/>
<rect width="2" height="2" x="1" fill="#fff"/>
<rect width="1" height="2" x="2" fill="#ce2b37"/>
</svg>
</div>