当前位置: 动力学知识库 > 问答 > 编程问答 >

css - 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

Expected result is

Please help. Thanks in advance

网友答案:

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)
}
网友答案:

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)
}
网友答案:

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)
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: