Snowcrash
Snowcrash

Reputation: 86097

Margin on child element added to parent DIV

I'm trying to get the H2 to appear half way down the DIV (i.e. so it appears vertically in the middle of the image) however, when I add a margin-top to the H2 it seems to add it to the DIV as well.

What's the problem and what's the solution?

<div>
    <div class="container">
        <style type="text/css" scoped>
            .container {
                background-image: url("http://lorempixel.com/500/250/business/");
                background-repeat: no-repeat; 
            }
            h2 { margin-top: 200px;}
        </style>
        <h2>Heading</h2>
        <p>Description</p>
    </div>
</div>

Upvotes: 1

Views: 51

Answers (1)

Jaqen H&#39;ghar
Jaqen H&#39;ghar

Reputation: 16804

  1. The problem is that the margins are collapsing:

Vertical margins on different elements that touch each other (thus have no content, padding, or borders separating them) will collapse, forming a single margin that is equal to the greater of the adjoining margins. This does not happen on horizontal margins (left and right), only vertical (top and bottom).

  1. The best solution which is not a hack is to change margin to padding and reset the default h2 margin-top:

    h2 { padding-top: 200px; margin-top:0;}
    
  2. If the padding is not suitable, there are some other possible solutions to prevent the default collapsing:

    • .container {border: 1px solid transparent}

    • .container {padding: 1px}

    • h2 {display: inline-block;}

  3. You say you wish to:

to get the H2 to appear half way down the DIV

It might be that a better to use percent to support different container sizes. Consider doing something like this:

.container {
   background-image: url("http://lorempixel.com/500/250/business/");
   background-repeat: no-repeat; 
   height:250px;
   position:relative;
}

.go-down { 
   top:50%; 
   position:absolute;
}
            
.go-down h2 {
   margin:0;
}
            
            
    
<div>
    <div class="container">
        <div class="go-down">
            <h2>Heading</h2>
            <p>Description</p>
        </div>
    </div>
</div>

Upvotes: 2

Related Questions