【问题标题】:center div in flex div while mantaining aspect ratio在保持纵横比的同时在 flex div 中居中 div
【发布时间】:2015-03-05 04:13:34
【问题描述】:

我试图将框“c”保持在“a”的中间,并使用 30px 10px 10px 10px 的内边距,以便它在顶部有更多的空间,而其他边的空间相等。但我希望框'c'不仅在这些边界之间,而且在'a'内垂直和水平居中,当你使框'b'宽度大于它缩小'a'和'c'时,保持c的纵横比,使“b”宽度更小并阻止“c”增长超过其限制并防止其溢出也是如此。此外,“b”的宽度/高度只会增长到 200 像素。

这是模板和我在 css 中的尝试:

<div class='z'>
<div class='a'>
    <div class='c'></div>
</div>
<div class='b'>
</div>

.z {
    display: flex;
    width: 300px;
    height: 200px;
}

.a {
    background-color: blue;
    padding: 30px 10px 10px 10px;
    flex: 1;
}

.b {
    background-color: yellow;
    width: 50%;
    max-width: 200px;
    transition: all 1s;
}

.c {
    background-color: red;
    margin: auto;
    width: 100%;
    padding-bottom: 100%;
}

这是我在 jsfiddle 中的尝试:http://jsfiddle.net/c8w79mLx/

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    您在寻找什么? FIDDLE

    除了对“a”框使用填充之外,我对 c 框使用了绝对定位:

    .c {
        background-color: red;
        margin: auto;
        padding-bottom: 100%;
        position:absolute;
        bottom:10px;top:30px;right:10px;left:10px;
    }
    

    【讨论】:

    • 不,我希望红色框始终居中,并且在拉伸时必须保持其纵横比宽度 = 高度。并且黄色框的宽度太小也不能溢出。
    【解决方案2】:

    将 a 类的 css 更改为:

    .a {
    background-color: blue;
    flex: 1;
    padding: 50px 10px;
    align-items: center;
    

    }

    对于 c 类:

    .c {
    background-color: red;
    width: 100%;
    height: 100%;
    

    }

    在这里更新小提琴 --> http://jsfiddle.net/c8w79mLx/6/

    【讨论】: