Flush first and last margin in CSS
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.
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;
}
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;}
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.
精彩评论