如何将div和img包装在display:flex容器中

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

编辑:您需要全屏运行该代码片段。

我有一个 display: flex 容器,其中包含 div 元素和其他包含 img 的容器,它们的宽度均为 50%。我希望它们在调整到 800px 以下宽度时具有 100% 屏幕宽度,并在新行上一个接一个地换行 (flex-wrap),但仍保持与换行之前一样的响应能力。

我尝试过,但我做错了 - 当屏幕宽度低于 800px 时,img 会获得应有的 100% 宽度,但第一个元素被隐藏,并且根本没有 flex-wrap。

#elegantImg{
    max-width: 100%;
    height: auto;
}

.elegant-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
}

.col {
    position: relative;
    width: 50%;
    height: auto;
    overflow: hidden;
}

.background {
    background-color: #F6F4F1;
    height: 100%;
}

.col img {
    width: 100%;
    height: auto;
    object-fit: cover;
}


@media screen and (max-width: 800px) {
    .col {
        width: 100%;
    }
}
        <section>
            <div class="elegant-container">
                <div class="col">
                    <div class="background"></div>
                </div>
                <div class="col">
                    <img id="elegantImg" src="https://i.imgur.com/TVL0phR.png" alt="">
                </div>
            </div>
        </section>

请帮忙:)

css flexbox display grid-layout
1个回答
0
投票

#elegantImg{
    max-width: 100%;
    height: auto;
}

.elegant-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
}

.col {
    position: relative;
    width: 50%;
    height: auto;
    min-height: 500px;
    overflow: hidden;
}

.background {
    background-color: #F6F4F1;
    height: 100%;
}

.col img {
    width: 100%;
    height: auto;
    object-fit: cover;
}


@media screen and (max-width: 800px) {
    .col {
        width: 100%;
    }
}
        <section>
            <div class="elegant-container">
                <div class="col">
                    <div class="background"></div>
                </div>
                <div class="col">
                    <img id="elegantImg" src="https://i.imgur.com/TVL0phR.png" alt="">
                </div>
            </div>
        </section>

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