首页 > 解决方案 > 我如何使用css将两个div放在彼此下方

问题描述

嗨,我在将两个 div 放在彼此下方时遇到问题。我有一个容器 div,它使用 display flex 和 justify content center 在页面居中,因为这是我可以让它工作的唯一方法。然后我有三个 div,一个占据屏幕的 50%,另外两个占据 20%,我希望其他两个 div 彼此下方而不是彼此相邻,但不知道如何做到这一点。这是我的 HTML:

<div id='content'>
    <div id='col1'>
        <p>paragraph 1</p>
    </div>

    <div id='col2'>
        <p>paragraph 2</p>
    </div>

    <div id='col3'>
        <p>paragraph 3</p>
    </div>

</div>

这是我的 CSS:

#content {
    display: flex;
    justify-content: center;
}

#col1, #col2 {
    float:left;
    margin-top:5px;
    margin-bottom:5px;
    border-radius:5px;
}

#col1 {
    width:50%;
}

#col2 {
    background: #FCF;
    width: 20%;
    height:250px;
}

#col3 {
    display:block;
    background: orange;
    width:20%;
    height: 250px;
    margin-top:5px;
    margin-bottom:5px;
    border-radius:5px;
}

提前感谢您的帮助。

标签: htmlcss

解决方案


如果我猜对了,为了让你的所有内容居中,你可以做这样的事情

#content {
margin-left: auto;
width:50%;
margin-right: auto;
}

#col1, #col2 {
margin-top:5px;
margin-bottom:5px;
border-radius:5px;
}

#col1 {
background: red;
}

#col2 {
background: #FCF;
width: 20%;
height:250px;
}

#col3 {
background: orange;
width:20%;
height: 250px;
margin-top:5px;
margin-bottom:5px;
border-radius:5px;
}

div 默认是一个块,所以不要使用 display:block,默认情况下 div 是相互堆叠的。如果你想让 2 个 div 彼此相邻使用 float: left 然后

<div style="clear:both"/>

恢复默认的 stack-on-top-of-other-other 行为

祝你好运!:)


推荐阅读