CSS:尝试将元素与大小不等的子元素垂直居中
P粉476046165
P粉476046165 2024-02-26 18:39:24
[CSS3讨论组]

大家好,这是我目前拥有的图片

我有一个 3 行 3 列的网格(每列是最小内容) 我将每个单元格中的元素居中。 看起来不错,但如果我的标题变得很大,开关和类别之间的空间就会变得太大:

现在我尝试在 div 容器内制作中间行并使用 flex,但元素不会居中,因为一个类别的大小比另一个类别的大小大。

我还尝试使类别大小相同,但是当我将整个组件集中在页面上的某个位置时,由于较小类别的空白,它会过于靠右。

知道如何使该空间变得更小,但将开关保持在标题和按钮的正中间吗?

代码如下:

HTML:

Male Female gender

以及 scss 代码:

.category-switch {
    // The grid to place the items
    display: grid;
    grid-template-columns: repeat(3, min-content);
    grid-template-rows: repeat(3, min-content);
    gap: 0.8rem;
    place-items: center;
    justify-items: center;
    // Makes the component be the width of its content
    width: max-content;

    // Title
    &__title {
        grid-row: 1/2;
        grid-column: 2/3;
        font-weight: bold;
        text-transform: capitalize;
    }

    // Placing category text
    &__category {
        &--1 {
            grid-row: 2/3;
            grid-column: 1/2;
        }

        &--2 {
            grid-row: 2/3;
            grid-column: 3/4;
        }
    }

    // The switch position
    &__switch {
        grid-row: 2/3;
        grid-column: 2/3;
    }

    // The button css
    &__btn {
        grid-row: 3/4;
        grid-column: 2/3;
        display: grid;
        place-items: center;
        position: relative;
        width: 7rem;
        height: 2.8rem;
        background: #d02b2b;
        border-radius: 0.5rem;
    }
}

尝试使代码尽可能少,并删除了一些与定位scss无关的内容。

P粉476046165
P粉476046165

全部回复(0)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号