Arun
Arun

Reputation: 3721

Place relative div on another div which fill that entire div

I have one div with class main-div and its sub div with class sub-div. sub-div contains some data. And I would like to append another div to sub-div which should cover the whole sub-div like a mask. I like do this with css. But i didn't get the actual result.

HTML

<div class="main-div">
    <div class="sub-div">
        jhgsdfjgjsdgfjgsdfgsdf<br />
        ugsdfgsdfgsgfjdgjfsdgsdf<br />
        jhgsdfjgjsdgfjgsdfgsdf<br />
        ugsdfgsdfgsgfjdgjfsdgsdf<br />
    </div>
</div>

CSS

.main-div{
    background-color: #F00;
    width: 100%;
    height: 300px;
}
.sub-div{
    background-color: #000;
    width: 50%;
    height: 200px;
    margin-left: 50px;
    color: #FFF;
}
.in-div{
    position: relative;
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 255, 0.5)
}

JavaScript

$(function(){
    var html = '<div class="in-div"></div>';
    $('.sub-div').append(html);
});

As per my knowledge, if I place a div with in another div, and give width and height as 100%, then it will have the width of the parent. Here when I give position: relative to in-div, it get the width and height of parent. But when the position become absolute or fixed, it broken.

My fiddle is http://jsfiddle.net/arunsankars1989/wfhfyf4a/

Current result is

enter image description here

Expected result is

enter image description here

Please help. Thanks in advance

Upvotes: 0

Views: 468

Answers (3)

himanshu
himanshu

Reputation: 1797

DEMO

.sub-div{
    background-color: #000;
    position: relative;
    width: 50%;
    height: 200px;
    margin-left: 50px;
    color: #FFF;
}
.in-div{
    position: absolute;
    top:0px;
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 255, 0.5)
}

Upvotes: 1

Vitorino fernandes
Vitorino fernandes

Reputation: 15951

demo - http://jsfiddle.net/wfhfyf4a/6/

set the position to absolute of .in-div and add top:0 so that the div align to the top of relative element

.sub-div{
    background-color: #000;
    width: 50%;
    height: 200px;
    margin-left: 50px;
    color: #FFF;
    position:relative; <-- added
}

.in-div{
    position: absolute; <-- change to absolute from relative
    top:0; <-- added
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 255, 0.5)
}

Upvotes: 1

kapantzak
kapantzak

Reputation: 11750

Just set position:relative to .sub-div, and a position:absolute to it's inner div (mask):

Check the DEMO

.sub-div{
background-color: #000;
position: relative;
width: 50%;
height: 200px;
margin-left: 50px;
color: #FFF;
}
.in-div{
position: absolute;
width: 100%;
top:0;
left:0;
bottom:0;
background-color: rgba(255, 255, 255, 0.5)
}

Upvotes: 1

Related Questions