在较小的屏幕上将两列合并为一列?

时间:2018-04-13 00:42:53

标签: html css

我正在尝试默认创建两列的布局。但是,在较小的屏幕上查看时,我只想让一列占据页面的整个宽度,然后将右列放在左列下面。我对html和css不是很了解。我发现这段代码可以让我设置列。但是我不知道如何让它们在较小的屏幕上堆叠成一个全宽列。也许我的方法开始时是错误的,并且有更好的方法来做到这一点。

<div style="display:flex;">
    <div style="flex-grow: 1;">
        <div class="box">
            Main content in left column here...
        </div>
        <div class="box">
            More main content here...
        </div>
        <div class="box">
            Even more main content here...
        </div>
    </div>
    <div style="width: 400px;">
        <div class="box">
            Some side content in the right column here...
            I would like this to stack under the main content on small screens...
        </div>
    </div>
</div>

1 个答案:

答案 0 :(得分:1)

您想要使用的是媒体查询,您可以在此处了解有关媒体查询的更多信息https://www.w3schools.com/css/css_rwd_mediaqueries.asp

<强> HTML

<div class="container">
    <div class="container__col-1">
        <div class="box">
            Main content in left column here...
        </div>
        <div class="box">
            More main content here...
        </div>
        <div class="box">
            Even more main content here...
        </div>
    </div>
    <div class="container__col-2">
        <div class="box">
            Some side content in the right column here...
            I would like this to stack under the main content on small screens...
        </div>
    </div>
</div>

如果您看起来我已经为您创建了一些课程

<强> CSS

.container{ // this is your main container that holds the two columns
    display: flex;
    flex-direction: row;
}
.container__col-1{ // this is your first column set to 50% width of the parent container
    width: 50%;
}
.container__col-2{ // this is your second column set to 50% width of the parent container
    width: 50%;
}
// this is a media query what this does is says when the screen size is smaller than 768px use these styles 
@media(max-width: 768px){ 
    .container{
       flex-direction: column;
    }
    // now your first column will take the full width of the parent 
    // container which will push the second column below it
    .container__col-1{ 
       width: 100%;
    }
    .container__col-2{
       width: 100%;
    }
}
显然,您需要将此更改为您的用例,但简而言之,您将如何做您想做的事