代码之家  ›  专栏  ›  技术社区  ›  Lordimass

创建一个1:1比例的图元,以另一个图元为中心

  •  2
  • Lordimass  · 技术社区  · 2 年前

    我正在尝试创建一些带有圆形的矩形框( 卵)盒子里。目前我的行为是: three rectangle with ovals inside spanning the whole area of the rectangle they're inside of 而我所期望的行为是圆形(即1:1的纵横比)。我的代码如下:

    #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
    }
    ```
    <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>

    看着其他类似的问题,我的印象是 aspect-ratio 是使用现代浏览器实现这一点的正确方法,但在我使用弹性框的时候,它似乎并不总是对我起作用,只要我换回标准框,圆圈就会起作用,但我无法将圆圈放在框的中心。

    我也读过关于使用 padding-bottom 技巧,但根本没有任何效果。除此之外,我读到一些答案,指出在该属性中使用百分比不起作用,也不应该使用,或者它已经过时 aspect ratio 应该改为使用。

    基本上,我不知道该怎么办,因为(从我所看到的)似乎只有两种可用的方法相互矛盾,但它们都不适合我。

    我也看到一些人提到使用JS可以实现这种行为,但我没有这方面的经验,所以如果能为我指明正确的方向,告诉我在CSS不可能的情况下如何编写脚本,那就太好了。

    提前谢谢。

    1 回复  |  直到 2 年前
        1
  •  4
  •   Paulie_D    2 年前

    您需要更改 align-items 从默认值 stretch center 或根据需要的任何其他值。

    #portals {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        justify-content: center;
    }
    
    .portal {
        display: flex;
        justify-content: center;
        align-items: start;
        width: 30%;
        border-radius: 1rem;
        background-color: aqua;
        height:25rem; /* 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>