简体   繁体   English

使用CSS同级选择器创建级联标题标记

[英]Creating cascading Heading tags with CSS sibling selectors

I am trying to create better flow of my headers, by indenting them a small amount depending on what the parent is. 我试图创建更好的标题流,通过缩小它们,取决于父级是什么。 For example H1 no indent, if H2 follows H1, then indent 1, else no... if H3 follows H1/H2 then indent, etc. so it cascades the indents appropriately. 例如H1没有缩进,如果H2跟随H1,则缩进1,否则没有......如果H3跟随H1 / H2然后缩进等,所以它适当地级联缩进。 Further it would cool if I could indent the content/p after every header tag... I have tried the following CSS after a bunch of research... 如果我可以在每个标题标记之后缩进内容/ p,那么它会很酷...我在一堆研究之后尝试了以下CSS ...

h1 {margin-left:0em;}
h1 ~ *:not(h1) {margin-left: 1em;}
h2 ~ *:not(h2) {{margin-left: 2em;}

Unfortunately this loses it's reach when another H1 is added... notice the following 不幸的是,当添加另一个H1时,它会失去它...请注意以下内容

Heading 1
    Heading 2.1
        Paragraph 2.1.1
        Paragraph 2.1.2
        Paragraph 2.1.3
    Heading 2.2
        Paragraph 2.2.1
        Paragraph 2.2.2
        Paragraph 2.2.3
        Heading 1.2 <this is wrong???
    Heading 2.1
        Paragraph 2.1.1
        Paragraph 2.1.2
        Paragraph 2.1.3
    Heading 2.2
        Paragraph 2.2.1
        Paragraph 2.2.2
        Paragraph 2.2.3

I want to try to do this without JS and only us CSS, is this possible? 我想在没有JS的情况下尝试这样做,只有我们的CSS,这可能吗?

I honestly don't entirely understand why you want to do this. 老实说,我不完全理解你为什么要这样做。 It seems cleaner to just always indent h2 elements. 总是缩进h2元素似乎更清晰。 But I'll assume you have your reasons. 但我会假设你有理由。 You can fix this by making the h1 selector more specific than the other selector so that it takes precedence: 您可以通过使h1选择器比其他选择器更具体来解决此问题,以使其优先:

html body h1 {margin-left:0em;color: red;}
h1 ~ *:not(h1) {margin-left: 1em;color: blue;}
h2 ~ *:not(h2) {margin-left: 2em;color: green}

In this way, even though the 2nd h1 matches both the first and 3rd selectors, the first now takes precedence since it is more specific. 这样,即使第二个h1与第一个和第三个选择器都匹配,第一个现在优先,因为它更具体。

http://jsfiddle.net/LUPD5/ http://jsfiddle.net/LUPD5/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM