Skip to content Skip to sidebar Skip to footer

Can Parent And Child Height Both Be In Percentage?

I'm trying to fill the image exactly to the full screen of the device. So i have given .container:100% and body,html to 100% height. Now i want to center align the child div vertic

Solution 1:

Margins in percentage are calculated according to the width of the container. see here

Percentages refer to the width of the containing block

(refering to margins)

So you can't use margins to verticaly center in CSS (except if you have fixed heights for conatiner and child).


To achive your goal

You can use absolute positioning

CSS for the child to verticaly center:

position:absolute;
top:25%;
left:0;
height:50%;
width:100%;

FIDDLE

In this fiddle I also made the scrollbars disapear by adding

body,html{
    margin:0;
    padding:0;
}

Solution 2:

Apart from missing :

margin:0;
padding:0;

in html, body, .container

looks pretty centered to me...http://jsfiddle.net/5LMY7/

Alternatively....

If you can fix the child height, then you can use calc to help you out :

.child {
    width: 100%;
    height: 50px; /* assuming fixed height */margin-top: calc(50% - 50px);
    margin-top: -moz-calc(50% - 50px);
    margin-top: -webkit-calc(50% - 50px);
    background-color: red;
    color:white;
}

Solution 3:

Try this code:

Fiddle:

body
{
    margin: 0px;
    padding: 0px;

}

.child{    
    width: 100%;
    height: 50%;
    top: 25%;
    bottom: 25%;
    background-color: red;
    color:white;
    position:absolute;
}

Post a Comment for "Can Parent And Child Height Both Be In Percentage?"