Reputation: 7385
What I want to do is target more than one <p>
with the following code:
h1+p
{
margin-left: 20px;
}
h2+p
{
margin-left: 27px;
}
h3+p
{
margin-left: 35px;
}
Below is the effect I am trying to achieve:
The problem is that when there is a new <p>
element, the block of text is obviously going to revert to it's normal position, without the margin, and not longer inline with the heading.
(like so)
Is there a better way of attacking this problem? (or one that works for that matter)
Upvotes: 1
Views: 118
Reputation: 724452
You can somewhat achieve this by using the general sibling selector ~
instead of the adjacent sibling selector +
:
h1~p
{
margin-left: 20px;
}
h2~p
{
margin-left: 27px;
}
h3~p
{
margin-left: 35px;
}
Be careful with this, though, especially if your h1
, h2
, h3
and p
elements all share the same parent. Due to the way that styles cascade as well as how sibling selectors work, all your p
elements that follow the last h3
element will get the 35-pixel margin, even if the last heading in your container is an h1
or h2
.
For instance, if you have this Markdown:
# Heading 1 Paragraph Paragraph ## Heading 2 Paragraph Paragraph ### Heading 3 Paragraph Paragraph ## Heading 2 Paragraph Paragraph
The last four paragraphs will have a 35-pixel margin, including the two that follow your last h2
, because your h3~p
rule is the last in the cascading order and all your elements share the same parent. This may or may not be the effect you're trying to achieve (I'm guessing it's not).
There isn't a pure CSS workaround for this, I'm afraid; you're going to have to post-process the rendered markup with JavaScript to add classes and such to your paragraphs based on your headings.
Upvotes: 4
Reputation: 386
is this what you are trying to achieve? http://jsfiddle.net/chrismackie/5DgNH/
Upvotes: 1