Jakob Nielsen
Jakob Nielsen

Reputation: 5198

div margin changing margin of parent div

I have a little problem which I don't know why it is happening. I have 2 div Wrappers, a so called "mainWrapper" which has an backround image and a child of this div called "loginWrapper". I want the login Wrapper to be positioned 15% from top, but if i simply add the margin, it seems to also change the margin of the parent div (mainWrapper).

Can somebody explain to me why this is happening, and how I can fix it?

Code:

HTML:

<div id="mainWrapper">
    <div id="loginWrapper">
        <h:graphicImage id="logo" alt="spotted deluxe" url="resources/images/logo.png" />
    </div>
</div>

CSS:

body,html{
    height:100%;
}

body {
    margin:0;
    background-color: green;
    background: url(../images/backround_red.png) no-repeat center center fixed;
    background-size: cover;
}

div#mainWrapper {
    text-align: center;
    margin: auto;
    width:70em;
    height:100%;
    background: url(../images/header.jpg) no-repeat center center fixed;
    background-size: cover;
    padding-left:4em;
}

div#loginWrapper {
    /*margin-top: 15%;*/
}

img#logo {
    display: inline;
}

Upvotes: 2

Views: 152

Answers (2)

Ilya Streltsyn
Ilya Streltsyn

Reputation: 13536

It's a special case of margin collapsing. Some options to prevent it are:

  1. Add 1px padding-top or border-top to the parent div
  2. Make the parent div establish the new block formatting context (e.g. by adding to it overflow: hidden or changing its display to display: table)
  3. Adding to the parent div the :before pseudo-element with display: table, as in the popular Micro Clearfix hack.

Upvotes: 2

AnilkaBobo
AnilkaBobo

Reputation: 260

yes, it will add margin to parent. Try position instead.\

 div#mainWrapper {
   position: relative;
 }

div#loginWrapper {
    position: relative;
    top: 15%;
}

Upvotes: 2

Related Questions