09 August, 2014

Columns side-by-side or stacked -- CSS to adjust for screen width

I recently had to brush up on my CSS skills to develop a solution where two buttons would appear side-by-side unless the view port was less than 480 pixels, in which case they should then display stacked. Through a bit of research I found a couple of solutions. When I tried to implement the solutions as presented, the buttons didn't appear side-by-side, but instead on separate rows -- I'm sure something I must of overlooked, but nevertheless I therefore came up with my own modified solution.

My particular example used 3 columns -- the middle just for space, which could be done with padding and/or margin. The key is using "@media." By default the widths of the columns were all set for 100% -- configured for stacking. When the screen was 480 pixels or larger, using "@media" the widths are adjusted 45%, 10%, and 45%. If you're not sure what each of these CSS properties do for you, try searching "css [property]" such as "css clear" and click on the link for w3schools -- usually the first or second response.

This should be enough to get you going. Depending on your use you may need to do further work, so when you;re on the 480+ pixel screen, you're not consuming all available width.

Class definitions

.mySection {
clear: both;
padding: 0px;
margin: 0px;
zoom:1; /* For IE 6/7 */
}

.mySection:before {
content:"";
display:table;
}
.mySection:after {
content:"";
display:table;
clear:both;
}

.myGroup {
display: block;
}

.grid_1of3, .grid_2of3, .grid_3of3 {
width:100%;
}

.grid_2of3 {
height:10px;
}

@media only screen and (min-width: 480px) {
.myGroup {
display: inline;
}

.grid_1of3,
.grid_3of3 {
width:45%;
}

.grid_2of3 {
width:10%;
}
}


HTML code

<div class="mySection" style="text-align:center;">
        <div class="myGroup grid_1of3"><img src="first_btn.png" border="0" /></div>
        <div class="myGroup grid_2of3"> </div>
        <div class="myGroup grid_3of3">< img src="second_btn.png" border="0" /></div>
</div>

No comments: