Selectively changing paragraph margins
A colleague of mine wanted to remove extra space between an unordered navigation list and the paragraph immediately above. But being semantically-minded, he didn’t want to add a special CSS class to tweak spacing.
The HTML (abbreviated for space):
<aside>
<p>Sample text that fills space.</p>
<p>Sample text that fills space.</p>
<ul>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ul>
<p>Sample text that fills space.</p>
</aside>
The site’s CSS put 10px of padding under every paragraph, and worked perfectly elsewhere in the site. We came up with three soltions:
- Apply
aside ul { margin-top: -10px; }. - Write jQuery that collapses the margin of the element immediately before the
<ul>.$('aside ul').prev().css('margin-bottom','0'); - Put the
<ul>at the top of the<aside>. Changing content to suit style was deemed a bad move.
He opted for solution #2. A week later when the site’s layout changed, removing a line of jQuery didn’t hurt the site.
How does that CSS work?
aside ul { margin-top: -10px; }
In English, this CSS means “give every unordered list ” inside every aside a negative ten pixel buffer. Negative values for margin-top are similar to position:relative; top:-10px, but also pull up everything beneath the affected element as well.
How does that jQuery work?
$('aside ul').prev().css('margin-bottom','0');
That means “find the element that preceeded every unordered list inside every aside and remove that element’s bottom margin.”
Tags: customizing layout problem solving