user5228393
user5228393

Reputation:

Why does position: relative make the height to zero?

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>

Upvotes: 2

Views: 3391

Answers (2)

Rocks
Rocks

Reputation: 1155

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.

Upvotes: 5

ankita patel
ankita patel

Reputation: 4251

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>

Upvotes: 1

Related Questions