2

So I am not a web developer and have very little experience with html and css so this might sound dumb:

But I saw code from my co worker who set a section to position:relative and the child element (an h1 in this case) to position: absolute; top: 0; left: 0; height: 100%; width:100% and somehow the h1 took the entire height and width of the parent which was the section.

I tried reproducing it below but it was not possible. Seems like the h1 has a height of zero since the border is not surrounding it. Is there something wrong with the code below?

<!DOCTYPE html>
<html>
<head>
<style>
    .main {
        background-color: blue;
        position: relative;
    }

    h1 {
        position: absolute;
        top: 0;
        left: 0;
        border: 1px solid black;
        height: 100%;
        width: 100%;
    }
</style>
<title>Page Title</title>
</head>
<body>
<section class="main">
    <h1>This is a Heading</h1>
</section>

</body>
</html>

2 Answers2

5

It is not the position: relative that is causing the problem but the position: absolute set on the h1.
If the parent container having the absolutely positioned child element doesn't have an explicit width and height set, it will collapse. This is because absolutely positioned elements are taken out of the normal flow of the document.
In order to solve your problem, you can explicitly set height/width on your .main.

Rocks
  • 1,145
  • 9
  • 13
  • Ah ok, this is what I wanted to know. Thank you so much for clarifying! –  Feb 24 '18 at 07:24
  • Also when you say `If the parent container having the absolutely positioned child element doesn't have an explicit width and height set, it will collapse.` Are you saying the parent component will collapse to zero or the child element? –  Feb 24 '18 at 07:34
  • 1
    The parent component will collapse if it has only absolutely positioned children, with no height/width set. – Rocks Feb 24 '18 at 08:26
1

Please remove position:absolute; top:0; left:0;height:0;width: 100%; this css to h1 class and your problem is solved.

<!DOCTYPE html>
<html>
<head>
<style>
    .main {
        background-color: blue;
        position: relative;
    }
    h1 {        
        border: 1px solid black;        
    }
</style>
<title>Page Title</title>
</head>
<body>
<section class="main">
    <h1>This is a Heading</h1>
</section>

</body>
</html>
ankita patel
  • 4,201
  • 1
  • 13
  • 28
  • Can you please explain why a little bit more? –  Feb 24 '18 at 05:48
  • 1
    Please check this URL for better understanding https://stackoverflow.com/questions/4457790/difference-between-style-positionabsolute-and-style-positionrelative . If you have still doubt then you can ask me. – ankita patel Feb 24 '18 at 05:54