Reputation: 39
I have DIV container with relative position, and the child with absolute position. here is my code source:
HTML:
<div class="wrapper">
<h1>Hello</h1>
</div>
CSS
.wrapper {
background: red;
width: 100px;
height: 100px;
position: relative;
}
.wrapper h1 {
color: #333;
position: absolute;
top: 60px;
}
when I put in top 60px, the child element jump to the bottom , normally the container has a relative position so the child element should be under the container not over the container.
Please, someone can explain me why this happen ? I hope I explained, well my question.
Upvotes: 0
Views: 391
Reputation: 43
Modern browsers, like Chrome and Firefox, are putting a 0.67em margin on top and bottom of h1 tags.
In your case declaring a margin 0 for .wrapper h1 will solve your problem.
Your code should be:
.wrapper {
background: red;
width: 100px;
height: 100px;
position: relative;
}
.wrapper h1 {
color: #333;
position: absolute;
top: 60px;
margin: 0;
}
If you are in doubt, use your browser's inspection / developer tools to find out what default stylings the browser is giving into any given element so you know which one you need to override.
Upvotes: 0
Reputation: 16029
Are you wondering why 60px from top of the div looks like 80px or 90 px? If this is your question, answer is easy. Browsers add some margin to h1, div and body elements. Simply clear that efect:
body, div, h1 {
margin: 0;
padding: 0;
}
Upvotes: 0
Reputation: 7352
When you have an element with position: absolute
that element is placed relatively to its closest positioned parent. A positioned element is any element with position
different from static
, be it relative
, absolute
or fixed
.
In your case you have a .wrapper
with position: relative
and h1
inside it with position: absolute
, that is why the latter is positioned 60 pixels from the top of its parent.
If you insist of the child element being below the parent, add z-index: -1
to it - http://jsfiddle.net/jt92sedr/4/
This property applies only to positioned elements.
You can check: http://www.barelyfitz.com/screencast/html-training/css/positioning/
Upvotes: 1
Reputation: 385
Try adding "margin:0; to the h1 element:
.wrapper h1 {
color: #333;
position: absolute;
top: 60px;
margin:0;
display:block;}
Upvotes: 1
Reputation: 21192
The CSS is actually doing what you think (sort of), but there is also (in Firefox, at least) a 21 pixel top margin which pushes the "text" down a bit farther.
Add a rule to remove the top margin:
.wrapper h1 {
color: #333;
position: absolute;
margin-top: 0; /* added this */
top: 60px;
}
Upvotes: 1
Reputation: 35572
Its the other way around, Relative always means relative to the parent. if you want to the child to be set in relation to parent, then make it relative.
the relative in your case on parent does not mean anything.
Upvotes: 0