CSS Notes

I. Inherit height of outer div

Problem: how to make an inner div to inherit the height of its containing div ?

  1. If containing div already specified height

    use height: 100% to inherit the outer div

  2. if containing div doesn’t specify height

    cannot use height: 100% to inherit the containing div. The computed height for the inner one will become auto, which means its height depends on its content

    If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to auto

    https://developer.mozilla.org/en-US/docs/Web/CSS/height

    Right way: containing div set position:relative; inner div set position: absolute and top:0 & bottom:0

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    <!DOCTYPE html>
    <html>
    <head>
    <style>
    #container{
    border: 1px solid red;
    position: relative;
    }
    #fullHeight{
    border: 1px solid green;
    position: absolute;
    top: 0;
    bottom: 0;
    width:100%;
    background-color: grey;
    opacity: 0.5;
    }
    #noHeight{
    height: 100%;
    width: 100%;
    border: 1px solid blue;
    }
    </style>
    </head>
    <body >
    <div id="container">
    <div id="noHeight" >ads </div>
    <div id="fullHeight"></div>
    <p>Dummy text. Dummy text. Dummy text. Dummy text. </p>
    </div>
    </body>
    </html>

II. Set mask to a div to disable it

Problem: set a mask layer to cover its outer div

Solution: use position: absolute & top: 0 & bottom: 0 to cover the whole height or its containing div, which set position: relative

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html>
<html>
<head>
<style>
#container{
border: 1px solid red;
position: relative;
}
#inner {
background-color: coral;
}
#mask{
border: 1px solid green;
position: absolute;
top: 0;
bottom: 0;
width: 100%;
height: 100%;
background-color: grey;
opacity: 0.5;
}
</style>
</head>
<body >
<div id="container">
<div id="inner" >myBox</div>
<div id="mask"></div>
<p>Dummy text. Dummy text. Dummy text. Dummy text. </p>
</div>

<script>
let inner = document.getElementById("inner")
inner.addEventListener("click", function(){alert("inner")})

let mask = document.getElementById("mask")
mask.addEventListener("click", function(){alert("mask")})

let container = document.getElementById("container")
container.addEventListener("click", function(){alert("container")})
</script>
</body>
</html>