tags:

views:

38

answers:

3

I would like to make the top element (wether it be a p, img, hx or whatever) flush with the top of the parent element while keeping it's normal separation between it's siblings.

For instance, I have a div full of p elements. Each p element has a top and bottom margin, say 10px. Each p element is separated by 20px (10 from the one above and 10 from the one below). The side effect of this is that the first p is pushed down by 10px and the bottom p is pushed up by 10px.

A: 

The simplest way to accomplish this is to only add bottom margins to your elements. So in your case, every p element would have a 20px bottom margin. This will also retain the 20px spacing between your p elements.

If you wish to remove the extra 20px added to the last p tag then you need to add a negative bottom margin to the container of the p elements.

.container {margin-bottom:-20px;}
.container p {margin-bottom:20px;}

You can also accomplish this by retaining the separate top and bottom margins but it makes your code more complex:

.container {margin-top:-10px; margin-bottom:-10px;}
.container p {margin-top:10px; margin-bottom:10px;}

In addition, this will work in all browsers whereas if you use special selectors, your CSS won't be applied to IE6 and the like.

Rupert
Ooh, nice gratuitous slams, @Rupert! Does "IE6 and 'the like'" mean all browsers that shipped over 9 years ago, all browsers with rapidly decreasing market share, all browsers [described by Microsoft as](http://www.computerworlduk.com/news/applications/20294/microsoft-internet-explorer-6-past-expiry-date/) obsolete security risks, or all browsers that Google doesn't support? Not to mention that you edited the beginning of your answer from "The way I usually do this…" to "The simplest way to accomplish this…"—one minute after I posted an answer starting "The simplest approach is…" *snicker*.
Dori
A: 

The simplest approach is to use a sibling selector:

p + p {
    margin-bottom: 10px;
    margin-top: 10px;
}

This rule applies to paragraphs only if they come directly after another paragraph. So, this rule doesn't apply to your first paragraph, as it doesn't follow a paragraph.

If you want space between every paragraph, but not before the first and not after the last, use this:

p + p {
    margin-top: 20px;
}
Dori
A: 

You could also use the :first-child and :last-child pseudo-selectors if that is ok with the browsers you support. Set the margin you want, then replace it for specific elements.

.container p{margin:10px 0;}
.container p:first-child{margin-top:0;}
Andy Atkinson