Reputation: 2587
I have been trying to figure out why setting margin-top: 100px on the p tag brings its parent element down with it. I can't figure it out. Anyone got any ideas?
HTML:
<div id="Sections">
<section id="Biography">
<div class="InnerLeftSection">
<p class="SectionTitle">Bio<br /><small>About Me</small></p>
</div>
<div class="InnerRightSection">
</div>
</section>
<section id="Blah">
<div class="InnerLeftSection">
<p class="SectionTitle">Blah<br /><small>Blah blah</small></p>
</div>
<div class="InnerRightSection">
</div>
</section>
</div>
CSS:
#Sections
{
width: 100%;
height: auto;
margin: -30px auto;
}
#Sections section
{
width: 200px;
height: 468px;
float: left;
margin-right: 15px;
opacity: 0.9;
}
#Sections #Biography .InnerLeftSection
{
background-image: url('/Shared/Assets/Images/BioTile.png');
background-repeat: no-repeat;
text-align: center;
width: 100%;
height: 100%;
background-color: blue;
}
#Sections #Biography .InnerLeftSection p
{
font-weight: bold;
}
#Sections #Biography .InnerLeftSection p small
{
font-weight: normal;
font-size:0.65em;
}
#Sections #Blah .InnerLeftSection
{
background-image: url('/Shared/Assets/Images/BlahTile.png');
background-repeat: no-repeat;
width: 100%;
height: 100%;
text-align: center;
background-color: green;
}
#Sections #Blah .InnerLeftSection p
{
font-weight: bold;
margin-top: 100px;
}
#Sections #Blah .InnerLeftSection p small
{
font-weight: normal;
font-size:0.65em;
}
Upvotes: 2
Views: 5282
Reputation: 30989
That's because of the collapsing margins of CSS Box model definition:
CSS 2.1 8.3.1 Collapsing margins
In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.
From the definition:
Margins of inline-block boxes do not collapse (not even with their in-flow children).
So change the display of p
to inline-block
to avoid this behavior.
Demo: http://jsfiddle.net/HU4pR/4/
Upvotes: 4
Reputation: 819
That's called collapsing margins: http://www.w3.org/TR/CSS2/box.html#collapsing-margins Vertical margins collapse but not horizontal margins.
To prevent that, you can set the parent overflow to overflow:auto
or overflow:hidden
, or just add the parent any border or padding.
See it here (overflow): http://jsfiddle.net/HU4pR/1/ Or here (padding): http://jsfiddle.net/HU4pR/2/
Upvotes: 2
Reputation: 11488
That is because of margin-collapse. When a block child is flush against side X of the parent block (assuming no border-/padding-X), the margin-X of the child will instead be applied to the parent. Just add this:
#InnerLeftSection { padding: 0.0001px }
Upvotes: 3