Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS - why does margin-top change the parent divs margin top?

Tags:

html

css

margin

This is my html:

<div id="Header">
    <div id="logoContainer">
        <p id="welcome">Welcome</p>
        <h1 class="logoText">first<img id="logoImage" src="image.jpeg" /><span id="second">second</span></h1>
    </div>
</div>

and this is my CSS:

#Header {
    font-family: consola;
    width: 100%;
    height: 50px;
    background-color: black;
    color: white;
}

#logoContainer {
    height: 50px;
    width: 200px;
    background-color: red;
}

#welcome {
    font-weight: 500;
    font-size: 8px;
    margin-bottom: -6px;
}

#logoImage {
    width: 14px;
    vertical-align: -4px;
    padding-left: 5px;
    padding-right: 5px;
}

.logoText {
    font-size: 12px;
    font-weight: 500;
}


#second {
    font-weight: 500;
}

Now, when I change

#logoContainer

to

#logoContainer {
    height: 50px;
    width: 200px;
    background-color: red;
    margin-top: 100px; // add a margin-top of 100px
}

the

#Header

and the

#logoContainer

get a margin-top of 100px

. How do I just give

#logoContainer

a margin-top of 100px?

like image 613
SilentDev Avatar asked Dec 20 '22 19:12

SilentDev


1 Answers

Total re-edit. So here's the deal with vertical margins.

Rule #1 - when two vertical margins in static or relative display elements meet (e.g. a bottom and top margin between two block elements in normal flow), the smaller of the two disappears.

Rule #2 - If a wrapping parent container doesn't have any padding or border, the same collapse thing thing happens to its top margin and its first child's top margin (and similar with last child and bottom margin). The smaller one disappears and the larger one takes its place. So a P tag with a 10px margin inside a DIV with no padding, or borders will actually push that parent DIV tag down as if the parent div had its own 10px top margin. If the parent div had had its own 15px margin but no padding or border, it would have been as if the P tag's margin had disappeared. 1px padding or border on the parent, however will stop this behavior because the two margins are no longer coming into contact with one another.

IMO, Rule #1 is great. You can basically have a bunch of content elements and always be certain that the larger whitespace need will be observed without any doubling up.

Also IMO, Rule #2 stinks. It doesn't come up quite as often as you'd think but it's really a bit of a nuisance when it does and still the reason I will sometimes only use margins on top or bottom in certain types of layout scenarios.

like image 76
Erik Reppen Avatar answered May 17 '23 06:05

Erik Reppen