创建一个 1:1 比例的元素,在另一个元素内居中

问题描述 投票:0回答:1

我正在尝试创建一些矩形盒子,里面有圆形(不是卵形)盒子。目前我得到的行为是这样的:three rectangle with ovals inside spanning the whole area of the rectangle they're inside of 而我期望的行为是圆圈(即 1:1 长宽比)。我的 HTML 如下:

<div id="portals">
    <div class="portal" id="art" style="background-color: #ce87e8;">
        <div class="portal-icon" id="art"></div>
    </div>
    <div class="portal" id="code" style="background-color: #87c8e8;">
        <div class="portal-icon" id="code"></div>
    </div>
    <div class="portal" id="projects" style="background-color: #e89f87;">
        <div class="portal-icon" id="projects"></div>
    </div>
</div>

还有 CSS:

#portals {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: center;
}

.portal {
    display: flex;
    justify-content: center;
    width: 30%;
    border-radius: 1rem;
    background-color: aqua;
    height:50rem;
    margin:1rem
}

.portal-icon {
    aspect-ratio: 1 / 1;
    width:90%;
    border-radius: 50%;
    background-color: white;
    margin:1rem
}

在查看其他类似问题时,我的印象是,

aspect-ratio
是使用现代浏览器实现此目的的正确方法,但在我使用弹性框时,它似乎并不一直对我有用。当我换回标准盒子时,圆圈起作用,但我无法使圆圈在盒子中居中。

我也读过有关使用

padding-bottom
技巧的内容,但它根本没有任何效果。除此之外,我读过一些答案,指出在该属性中使用百分比不起作用且不应该使用,或者它已经过时,应该使用
aspect ratio
来代替。

基本上我不知道该怎么做,因为似乎仅有的两种可用方法在应该使用的问题上相互矛盾(据我所知),但它们都不适合我。

我也看到一些提到可以使用 JS 来实现这种行为,但是我对此没有任何经验,所以如果我能指出正确的方向,我应该如何编写一个脚本来做到这一点 CSS不可能,那就太好了。

提前谢谢您。

javascript html css flexbox
1个回答
0
投票

您需要将

align-items
默认值更改为
center

#portals {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: center;
}

.portal {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 30%;
    border-radius: 1rem;
    background-color: aqua;
    height:15rem; /* adjusted for demo */
    margin:1rem
}

.portal-icon {
    aspect-ratio: 1 / 1;
    width: 90%;
    border-radius: 50%;
    background-color: white;
    margin:1rem
}
<div id="portals">
    <div class="portal" id="art" style="background-color: #ce87e8;">
        <div class="portal-icon" id="art"></div>
    </div>
    <div class="portal" id="code" style="background-color: #87c8e8;">
        <div class="portal-icon" id="code"></div>
    </div>
    <div class="portal" id="projects" style="background-color: #e89f87;">
        <div class="portal-icon" id="projects"></div>
    </div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.