Targeting more than one next element with element +
I want to do 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 a new element <p>
appears, the block of text will obviously revert to it in its normal position with no margin and will no longer be on the line with the title.
(eg)
Is there a better way to attack this issue? (or one that works for that matter)
source to share
You can achieve this somewhat by using a generic selector ~
instead of an adjacent sibling selector +
:
h1~p
{
margin-left: 20px;
}
h2~p
{
margin-left: 27px;
}
h3~p
{
margin-left: 35px;
}
Be careful with this, especially if your items h1
, h2
, h3
and p
all have the same parent. Because of the way cascading styles, as well as how selector rollers work, all of your elements p
that follow the last element h3
will get a 35px edge, even if the last heading in your container is equal to h1
or h2
.
For example, 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 35px margin, including the two that follow your last h2
one because your rule h3~p
is the last one in a cascading order and all of your elements have the same parent. This may or may not be the effect you are trying to achieve (I assume it is not).
There is no CSS workaround for this, I'm afraid; you will have to post the rendered markup with JavaScript to add classes, etc. into your paragraphs based on your headings.
source to share