Brandon Dorsey
Brandon Dorsey

Reputation: 153

Why are my margins still collapsing?

My code in this "Fiddle" shows that I have adjacent elements which vertical margins are collapsing on one another. I understand that due to the nature of vertical margins in css, the largest of the two is chosen, In my case the p tag.

What I am having trouble with is trying to break the margins by using a 1px border or 1px padding. I've seen it work with other workarounds such as position:absolute or float method. I am not understanding why using 1px border or padding is not working properly to give me 15px of space.

Upvotes: 1

Views: 103

Answers (3)

SaidbakR
SaidbakR

Reputation: 13544

To make them displayed next to each other change the following:

p {
    margin-bottom: 10px;
    display:inline;
}

div {
    padding: 1px;
    margin-top: 5px;
    display:inline;
}​

Upvotes: -1

Ivan Shcherbakov
Ivan Shcherbakov

Reputation: 2713

There is a some techniques to prevent collapsing of the margins. You said about two of them: absolute position and float. In addition you can use display: inline-block for your p tags. In this guide I found the solution with borders and paddings only for nested elements. And, of course, you can use really big borders instead of margins :)

Upvotes: 2

kinadian
kinadian

Reputation: 238

Are you looking to use a border or background on either the p or div? If not, use a padding in one or both of your styles. Padding does not collapse like margins do.

p {
    padding-bottom: 10px;
}
div {
    padding: 1px;
    margin-top: 5px;
}​

If you do include a border or background, using padding might not give the look you're going for because borders are outside of the padding and backgrounds include the padding area.

Upvotes: 0

Related Questions