将ID或类添加到Markdown元素

39

是否可以向(Multi)Markdown元素添加id或class?

例如表格、段落或代码块?

我想使用CSS样式来美化表格,但以下任何一种方法都不起作用:

[captionid][This is the caption, not the table id]
| First Header  | Second Header |
| ------------- | ------------- |
| Content Cell  | Content Cell  |
| Content Cell  | Content Cell  |

| First Header  | Second Header |
| ------------- | ------------- |
| Content Cell  | Content Cell  |
| Content Cell  | Content Cell  |
[captionid][This is the caption, not the table id]

| First Header  | Second Header |
| ------------- | ------------- |
| Content Cell  | Content Cell  |
| Content Cell  | Content Cell  |
[tablecaption](#tableid)

<div class="special_table">

| First Header  | Second Header |
| ------------- | ------------- |
| Content Cell  | Content Cell  |
| Content Cell  | Content Cell  |

</div>

在网上找不到其他东西了...

我指的不是Github或StackOverflow风格的Markdown。

4个回答

14

为了CSS的目的,您可以给前一个元素添加一个id,然后使用选择器来修改接下来的元素。

像这样的Markdown:

<div class="special_table"></div>

| First Header  | Second Header |
| ------------- | ------------- |
| Content Cell  | Content Cell  |
| Content Cell  | Content Cell  |

这样的 CSS:

div.special_table + table tr:nth-child(even) {background: #922}

8
您可以通过在元素后面加上花括号,将自定义的类或id添加到元素中,如下所示:{#id .class}
例如:
[Read more](http://www.stackoverflow.com "read more"){#link-sf .btn-read-more}

将呈现如下:

<a href="http://www.stackoverflow.com" title="阅读更多" id="link-sf" class="btn-read-more">阅读更多</a>

您可以参考https://michelf.ca/projects/php-markdown/extra/#spe-attr


2
个人而言,这个在Docusaurus上不起作用 :( - Some Dev
3
这对于表格会怎么样? - SCI
在mkdocs上也无法工作。 - undefined

6

经过一些研究,我提出了一个简单而直接的解决方案 :)

我在两个HTML占位符之间放置了表格,并使用jQuery对其进行微调,仅在需要时进行微调:

表格开头

<div class="tables-start"></div>

表格

id | 名称 ---|--- 1 | 伦敦 2 | 巴黎 3 | 柏林

表格结束

<div class="tables-end"></div>

jQuery: 通过添加类来微调表格

<script type="text/javascript">
(function() {
    $('div.tables-begin').nextUntil('div.tables-end', 'table').addClass('table table-bordered');
})();
</script>

只需使用div包装Markdown表格 :) ? 然后是 .foo table { color: red; } - 为什么要用JavaScript? - Badr Hari
1
很好的观点@BadrHari,但问题明确要求如何向Markdown元素添加“Class”或“Id”;) - wik
1
应该使用 $('div.tables-start'),而不是 $('div.tables-begin')。 - Johnny
@BadrHari - 我在mkdocs-material下尝试过,但附带的markdown没有被翻译成html。 - Craig Hicks

0
我正在使用just the docs,解决方案有点不同。DAMIEN JIANG 指引了我正确的方向。这对我有用: [[2]](references#2){: #references-2 } 它渲染成: <a href="references#2" id="references-2">[2]</a>

1
这个也在docusaurus上不起作用。 - Some Dev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接