user1227445
user1227445

Reputation: 453

Combine two columns into one on smaller screens?

I'm trying to create a layout of two columns by default. However, when viewing on a smaller screen, I'd like to just have one column take up the full width of the page and then just stack the right column under the left column. I'm not very good with html and css. I found this code that let me set up the columns. However I have no idea how to get them to stack into one full width column on smaller screens. Perhaps my approach is wrong to begin with and there is a better way to do it.

<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>

Upvotes: 0

Views: 3474

Answers (1)

Smokey Dawson
Smokey Dawson

Reputation: 9230

What you want to use are media queries you can learn more about media queries here 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>

If you look I have created some classes for you

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%;
    }
}

obviously you will need to alter this to your use case but this is in a nutshell how you would do what you want

Upvotes: 3

Related Questions