Search code examples
csshtmlalignment

How to align content inside two divs of different width at 50% height?


There are two div-containers: leftcontainer covers the left half of my screen, rightcontainer the right half. Inside both containers is a textbox with variable height

.leftcontainer{
    position: relative;
    float:left;
    width:60%;
    height:100%;
}
.rightcontainer{
    position: relative;
    float: right;
    width:40%;
    height:100%;
}
.textbox{
    margin-top: 50%;
    width: 100%;
    background:#333333;
}
<div class="leftcontainer">
    <div class="textbox">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore
    </div>
</div>
<div class="rightcontainer">
    <div class="textbox">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore
    </div>
</div>

I want the textboxes to be horizontally aligned: both should start at 50% height. But they are only aligned, if I set the width of leftcontainer and rightcontainer both to 50%.
If I do

.leftcontainer{width:60%;}
.rightcontainer{width:40%;}

the right text box moves up. Could someone tell me, how to fix this? Thank you.


Solution

  • If you are using the containers to span the entire visible height of the window, then this is easy to accomplish by switching the height and margin-top units from % to vh which is a unit that represents 1/100th of the the view-port height.

    .leftcontainer{
        position: relative;
        float:left;
        width:60%;
        height:100vh;
    }
    .rightcontainer{
        position: relative;
        float: right;
        width:40%;
        height:100vh;
    }
    .textbox{
        margin-top: 50vh;
        width: 100%;
        background:#333333;
    }
    

    http://jsbin.com/ahAfUba/1/edit?html,css,output