我有一些css代码,增加了H1-H6标题的页边距。我想看看是否有办法使这一条更短、更干净,而不必每次都重复同样的规则。也许有个变数。
对不起,我是新来的,我不知道这是否真的能办到。下面我发布了一些我尝试过的代码,它们都很好,但我不认为这是最佳的实践。有更好的方法吗?我相信,对这个问题进行更好的管理对于css的许多其他方面都是有用的。
我试过这个
.article-heading > div h1 { margin-bottom: 12px!important; }
.article-heading > div h2 { margin: 24px 0px 12px 0px!important; }
.article-heading > div h3 { margin: 24px 0px 12px 0px!important; }
.article-heading > div h4 { margin: 24px 0px 12px 0px!important; }
.article-heading > div h5 { margin: 24px 0px 12px 0px!important; }
.article-heading > div h6 { margin: 24px 0px 12px 0px!important; } 还有这个
.article-heading > div h2, .article-heading > div h3, .article-heading > div h4, .article-heading > div h5, .article-heading > div h6 { margin: 24px 0px 12px 0px!important; } 发布于 2022-06-25 12:28:03
请试如下:
.article-heading>div h1 {
margin: 0px 0px 12px 0px!important;
}
.article-heading>div :is(h2, h3, h4, h5, h6) {
margin: 24px 0px 12px 0px!important;
}<div class="article-heading">
<div>
<h1>Hello World!</h1>
<h2>Hello World!</h2>
<h3>Hello World!</h3>
<h4>Hello World!</h4>
<h5>Hello World!</h5>
<h6>Hello World!</h6>
</div>
</div>
new :is() CSS伪类可以在一个选择器中完成。
上面是如何针对容器元素中的所有标题的示例。
大多数浏览器现在都支持:is(),但是请记住,2020年以前的大多数浏览器都不支持没有前缀的浏览器,所以如果需要支持旧的浏览器,请小心使用它。
在某些情况下,您可能希望使用:where()伪类,它非常类似于: is (),但具有不同的专用性规则。
发布于 2022-06-25 12:28:44
根据您的问题,根据我的经验,有两个答案:1. **在简单的HTML / CSS **中,您可以使用var(),例如:<style> :root{--marginElement:24px 0px 12px 0px;}</style>可以在margin:var(--marginElement);的特定页面上任意使用它,
在react中,您只需在像const marginElement = {margin:"24px 0px 12px 0px"}这样的对象中创建一个变量存储值,并以attr的方式使用它。
发布于 2022-06-25 12:36:51
我不知道你的HTML是什么样子。一个快速的解决方案是创建一个类似于margin的类,然后在需要使用该类的地方使用HTML中的类。
就像这样:
.article-heading>div .margin {
margin: 24px 0px 12px 0px!important;
}<div class="article-heading">
<div>
<h1 class="margin">Heading 1 using .margin</h1>
<h2 class="margin">Heading 2 using .margin</h2>
<h3 class="margin">Heading 3 using .margin</h3>
<h4 class="margin">Heading 4 using .margin</h4>
<h5 class="margin">Heading 5 using .margin</h5>
<h6 class="margin">Heading 6 using .margin</h6>
</div>
</div>
https://stackoverflow.com/questions/72753754
复制相似问题