简体   繁体   中英

Floating div doesn't change its height to 100%

I want a floated div to have the full height of its parent.

Link to the JSFiddle I created: http://jsfiddle.net/Em6ms/2/

div.second {
    float: left;
    width: 150px;
    height: 100%;
    /* <- Problem: This does not work! */ }

That's how I want it look: http://www.directupload.net/file/d/3646/yqfogsew_png.htm

I know there are lots of questions about this problem but not one answer worked on my specific case. I tried

html, body {height: 100%;}

and adding an additional div with the "clear: both" instruction.

Thank you!

If you don't specify the height of the parent div, you cannot set the child to have its height 100% relative to its parent. One way to fix this if the size of parent is not specified is using jquery:

$('document').ready(function(){
    $(".second").css('height', $(".first").css('height'));
});

Live demo

Using pure javascript:

var firstHeight = document.getElementsByClassName('first')[0].clientHeight-20;

var test = document.getElementsByClassName('second')[0].style.height = firstHeight+"px";

Live demo

Live Demo

you must set height for your parrent element (for example : body ), then use height:100% !!

CSS:

body{
    height:500px;

}
div.first {
    position:relative;
    height:200px;
    max-width: 950px;
    margin-left: auto;
    margin-right: auto;
    margin-top: 2%;
    border-color: black;
    border-style: solid;
    border-width: 1px;
    box-shadow: 1px 1px 2px 2px;
    padding: 1%;
}
div.second {
    position:absolute;
    background:green;
    width: 18%;
    height:98%;
    top:1%;
    left:1%;
    border-right-color: red;
    border-right-style: solid;
    border-right-width: 5px;
}
div.third {
    position:absolute;
    width:78%;
    height:98%;
    top:1%;
    right:1%;
    text-align: center;
    background:#e7e7e7;
}

height: 100%; means the element gets as high as its parent element. So you have to set the height of all parent elements to 100% too.

Your parent elements are not only body, html but also .first .

So just add

html, body, .first {
    height: 100%;
}

and it works!

But there is another problem too: You can't set the height of an element to 100% and also add some padding , margin or border . They need space so the element gets larger then 100%.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM