de.vina
de.vina

Reputation: 116

CSS: "AND" and + operator?

I want to put a space after all the headers using CSS. Like this:

if h1 = add a space after
else if h1 + h2 = add a space after also but no space in between

This is my HTML code

<article>
     <h1>Title 1</h1>
...
</article>
<article>
     <h1>Title 1</h1>
     <h2>Title 2</h2>
...
</article>

For the CSS

h1, h2 { padding-bottom: 20px; }

The problem is, there is a space also between h1 and h2. I tried this code below but only those articles with h1 and h2 have a space after.

h1 + h2 { padding-bottom: 20px;}

Is there a way to do this? Or I should just use the h1 + h2 in CSS and add < br > for h1 only?

Upvotes: 2

Views: 2196

Answers (2)

Domenic
Domenic

Reputation: 112857

There's a few ways to do this, none pretty.

/* #1 */
h1 + *:not(h2),
h2 + *:not(h3) { /* etc */
    padding-top: 20px;
}

/* #2 */
h1, h2 {
    padding-bottom: 20px;
}
h1 + h2 {
    margin-top: -20px;
}

(and variations of these.)

The problem is there is currently no way to select "backward," i.e. apply styles to an element based on what appears after it. There is only the ability to select "forward," using the + or ~ sibling combinators. So you can't override the style on an <h1> based on the existence of a subsequent <h2>.


In the CSS4 selectors draft, there is a method of specifying the subject of the selector, using the $ sign. In that case the code would look like:

h1, h2 {
    padding-bottom: 20px;
}
$h1 + h2 {
    padding-bottom: 0;
}

/* or even */
h1:not($h1 + h2), h2 {
    padding-bottom: 20px;
}

This isn't currently available in any browsers, however.

Upvotes: 2

Collin Green
Collin Green

Reputation: 2196

Is there no way to know when generating the HTML if the h2 is following the h1? That seems like the best way to handle this. Then you can make a simple css rule for h2.follows_h1 { margin-top: -5px } or whatever fits exactly what you need.

Upvotes: 0

Related Questions