views:

32

answers:

1

Hi,

This is a basic but tricky question about styling header with General Sibling Selector. Many people make a mistake about using it (and write books!). It seems for me useless:

<h1>Title 1</h1>
<p>text</p><p>text</p>
<h2>Title 1.1</h2>
<p>text</p><p>text</p>
<h3>Title 1.1.1</h3>
<p>text</p><p>text</p>
<h2>Title 1.2</h2>
<p>text</p><p>text</p>
<h3>Title 1.2.1</h3>
<p>text</p><p>text</p>

I would like to style all my P with a margin:

H1 ~ P { margin-left: 1em; }
H2 ~ P { margin-left: 2em; }
H3 ~ P { margin-left: 3em; }

It simply can't work !

Because P of section 1.2 are after a H3 and styled by H3 isntead of H2.

  • I can't use H2+P because I can have many P.
  • I don't want to use <div> around the P it's too cludge.
  • if I do not put a wraper on this code all P in the page after this code will be selected !

Is there a way to scope Tilde ? Or handle this issue smartly?

A: 
  • correct your HTML, the closing-tags are wrong

  • try to turn the css the other way around (the last definition wins, so i think this works (but i havn't tested))

new CSS:

h3 ~ p { margin-left: 3em; }
h2 ~ p { margin-left: 2em; }
h1 ~ p { margin-left: 1em; }

EDIT: not a big problem, but you should try to keep Captain Capslock out of your CSS... the tags are <p> and <h1> - why do you wite P and H1 in your css-selector?

oezi
The order Jean-Phillippe Encausse had originally would override correctly if the headings were simply sequential, but in his (more realistic) markup the headings switch back and forth from `h3` to `h2`.
VoteyDisciple
Well about CSS typo I like to Uppercase Tags because it is a very good way to improve readability: Tag uppercase, Class camelcase or lowercase (PRE.first {} or A.link IMG.icon {}).
Jean-Philippe Encausse
About answer, basically the html can have many h1-6 tags, so it could be <h1><h2><h3><h1><h2><h3>...<P>. At last, P is next to a h1 and a h2 and a h3. So, any way you change order of CSS declaration it can't work because the last declaration will win. It seems, the only way to make it work would be if a declaration of h1-6 override an over declaration of h1-6.
Jean-Philippe Encausse