【问题标题】:Indent everything after h1, h2, etc. before the next, one, while stacking the indents, with CSS在 h1、h2 等之后的所有内容在下一个之前缩进,一个,同时堆叠缩进,使用 CSS
【发布时间】:2021-10-27 00:35:26
【问题描述】:

我有一个可以编译成 HTML 文件的 markdown 文件。但是,当我这样做时,不清楚哪个段落属于哪个标题。如果在第一个小标题之后有一个副标题,我想将其向右轻推后的内容向右移动。

# H1
## H2
text
## H2

h1 ~ *, h2 ~ *, h3 ~ *, h4 ~ *, h5 ~ *, h6 ~ * {
    text-indent: 16px;
}
<h1>H1</h1>
<h2>H2</h2>
<p>text</p>
<h2>H2</h2>

预期输出:

H1

 H2

  文本

 H2

实际输出:

H1

H2

文字

H2

【问题讨论】:

  • 段落不总是跟在标题后面吗?我不明白这个问题。无论如何,您尝试过什么?请使用您的 CSS 创建一个正常运行的 sn-p。
  • 另外,除了 H1 标题之外,您不是只是缩进 所有内容 吗?这是很琐碎的事情。有什么问题?
  • @isherwood 不,我正在尝试在 h1s 之后缩进 h2s,在 h2s 之后缩进 h3s,等等
  • h1 ~ *:not(p) {text-indent: 16px;},这是您要找的吗?
  • 您必须为每个元素指定缩进量,它们不会堆叠,因为 h1、h2、h3 等没有作为子元素的元素。

标签: html css markdown


【解决方案1】:

我认为你真正想要的只是每个逐渐降低的标题缩进相同的数量,并且段落相对于它们后面的任何标题缩进。我们将使用 subsequent sibling combinator (~),就像你做的那样,它只选择选择器之后的兄弟姐妹。

为了标准可读性,同一级别的所有标题都应缩进相同的数量。在这方面,段落可能不太重要。例如,我假设您将遵守正确的文档结构,而不是在 H1 之后立即放置 H3。

这里我使用custom property* 定义了一个CSS 变量,这样缩进因子就可以在一个地方更新并为每个规则计算。我选择使用rem 单位来实现跨元素类型的大小一致缩放,但您当然可以使用em 单位进行可变缩进,或者干脆使用px

:root {
  --indent-unit: 1rem;
}

h2 {
  text-indent: calc(var(--indent-unit) * 1);
}

h2~p,
h3 {
  text-indent: calc(var(--indent-unit) * 2);
}

h3~p,
h4 {
  text-indent: calc(var(--indent-unit) * 3);
}

h4~p,
h5 {
  text-indent: calc(var(--indent-unit) * 4);
}
<h1>Heading Level 1</h1>
<h2>Heading Level 2</h2>
<p>Paragraph.</p>
<p>Paragraph.</p>

<h3>Heading Level 3</h3>
<p>Paragraph.</p>
<p>Paragraph.</p>

<h2>Heading Level 2</h2>
<h3>Heading Level 3</h3>
<h4>Heading Level 4</h4>
<p>Paragraph.</p>
<p>Paragraph.</p>

*Internet Explorer not supported,但we don't care

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-18
    • 2013-08-11
    • 1970-01-01
    • 2022-01-19
    • 2021-07-16
    • 2016-06-23
    • 1970-01-01
    • 2020-01-25
    相关资源
    最近更新 更多