Shirohige Shirohige - 3 months ago 7
CSS Question

Left, right and center aligned divs

I'm trying to create a page that has multiple 3 divs in a row, which are left right and center aligned.

I tried using

float:left
and
float:right
but it worked out really bad. The page scales super randomly and I want the divs to become in 2 columns when the page scales down and then to 1 column for mobile devices.



.container {
display: inline-block;
text-align: center;
width: 100%;
position: relative;
}
.left,
.middle,
.right {
width: 200px;
height: 200px;
background-color: red;
display: inline-block;
}
.left {
float: left;
}
.right {
float: right;
}

<div class="container">

<div class="left">
<div class="content">
</div>
</div>
<div class="middle">
<div class="content">
</div>
</div>
<div class="right">
<div class="content">
</div>
</div>

</div>





jsFiddle: https://jsfiddle.net/azizn/j4cgef5g/

Answer

Check out the examples I've included below (CSS and HTML script)

HTML

<div id='columns'>
    <div id='col1'></div>
    <div id='col2'></div>
    <div id='col3'></div>
</div>

CSS

#columns{
    position: absolute;
    height: 100%;
    width: 100%;
}

#columns #col1{
    float: left;
    width: 33.33%;
    height: 100%;
}


#columns #col2{
    float: left;
    width: 33.33%;
    height: 100%;
}


#columns #col3{
    float: left;
    width: 33.33%;
    height: 100%;
}

@media media only screen and (max-width:1024px) and (min-width:540px){
    #columns #col1{
        width: 50%;
    }


    #columns #col2{
        width: 50%;
    }


    #columns #col3{
        width: 100%;
    }
}

@media media only screen and (max-width:540px){
    #columns #col1{
        width: 100%;
    }


    #columns #col2{
        width: 100%;
    }


    #columns #col3{
        width:  100%;
    }
}

Take note I haven't actually tested the above example, but it should work. You can edit your width and height values as you wish, as well as the widths for the media queries. As the screen gets smaller, it removes the columns 3 and 2 from display, while making the other columns larger. To make the three columns in left, center and right positions you don't need to specify different floats, as being in blocks they will automatically collide and stack at the left until they hit the screen edge. This is also why the width can generally only be 33.33%, as going to 33.333% will generally make the third block be pushed down as there isn't enough space. In most cases, the 0.01% dead space isn't noticeable anyway.