Reputation: 25
I need to convert a 3-column fixed width layout to a responsive one and have been frying my brain trying to understand all the various ways people are going about this. The column widths are roughly 22% - 56% - 22% of the container div width. When displaying in a smartphone context, I want columns 1 and 3 to appear together side by side taking up 50% of the screen width each, then column 2 (the main content) to appear below at 100% of width.
Can anyone advise the best way to go about achieving this? Do I need to swap columns 2 and 3 around to get them to flow the way I want them to? Or is there another way that works as well without having to go through and change the markup of the entire site? I would like to use CSS only solutions if possible. Thanks.
Upvotes: 1
Views: 3807
Reputation: 12923
You can do this with media queries and floats. Using float: left
and float: right
you just need to set up your HTML properly. The trick is to float column 1 to the left and two and three to the right with three coming before two in your html:
HTML
<div class="wrapper">
<div class="one"></div>
<div class="three"></div>
<div class="two"></div>
</div>
CSS
.one{
float: left;
background: red;
width: 22%;
height:100px;
}
.two{
float: right;
background: blue;
width: 56%;
height:100px;
}
.three{
float: right;
background: green;
width: 22%;
height:100px;
}
@media only screen and (max-width: 300px){
.one{
width: 50%
}
.two{
width: 100%
}
.three{
width: 50%
}
}
UPDATE
As Crispy-George posted you could use flexbox
but it does have limited browser support and basically doesn't work with IE 9 and below:
Upvotes: 1
Reputation: 2058
If you have to maintain a strict order on your columns, like:
<div class='box box-1'>Small box</div>
<div class='box box-2'>Yeah, I'm the big box</div>
<div class='box box-3'>Even Smaller box</div>
you can use flexbox
to change the order
of these boxes on your desired screen resolutions, however I believe it has no support for lower than IE9, but if you dont have to support older browsers, check out the demo here.
The markup:
<div class='container'>
<div class='box box-1'>Small box</div>
<div class='box box-2'>Yeah, I'm the big box</div>
<div class='box box-3'>Even Smaller box</div>
</div>
And the css stuff:
.container{
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-flex-wrap: wrap;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
}
.box{
min-height: 200px;
font-size: 18px;
}
.box-1{
width: 25%;
background: red;
}
.box-2{
width: 60%;
background: teal;
}
.box-3{
width: 15%;
background: cyan;
}
@media all and (max-width: 768px){
.box-1{
-webkit-order: 1;
-ms-order: 1;
order: 1;
width: 50%;
}
.box-3{
-webkit-order: 2;
-ms-order: 2;
order: 2;
width: 50%;
}
.box-2{
-webkit-order: 3;
-ms-order: 3;
order: 3;
width: 100%;
}
}
Upvotes: 1