几乎相同的嵌套选择器的CSS规则

时间:2019-05-25 02:30:30

标签: html css css3

我正在尝试为网站编写更简单的响应式CSS规则,我需要做到以下几点,减少重复的文字:

break when x = "the dog runs"

我的意思是:将位于.centertext元素内的.wpb_wrapper元素内的每个heading1,heading2,heading3和段落居中。

我确定必须在“ .centertext .wpb_wrapper”和所有这些家伙之间添加一个符号或一些简单的符号(或者空格字符也应该消失吗?),但我不知道它是什么。请帮忙!

先谢谢了。 J

3 个答案:

答案 0 :(得分:0)

您可以通过comma-separating the selectors减少重复次数,并一次声明规则:

.centertext .wpb_wrapper h1,
.centertext .wpb_wrapper h2,
.centertext .wpb_wrapper h3,
.centertext .wpb_wrapper p {
  text-align: center !important;
}

但是为什么不这样呢?

.centertext {
  text-align: center;
}

如果不是总是居中文本,为什么要使用名为centertext的类?

答案 1 :(得分:0)

为什么不只是:

@media only screen and (max-width: 767px) {
  .centertext {text-align:center;}
}

如果您的h1 / h2 / h3等上没有其他规则可以覆盖它,它将被继承。如果您有其他规则冲突,则可以简化对CSS的重新排序或确保冲突具有类似的媒体查询限制。

除非没有办法解决,否则我通常会尽量避免!important。通常,只有在您无法控制所有影响网站的代码时,这才是正确的。

答案 2 :(得分:0)

您可以使用以下代码来缩短代码

@media only screen and (max-width: 767px) {
  .centertext .wpb_wrapper h1,
  .centertext .wpb_wrapper h2,
  .centertext .wpb_wrapper h3,
  .centertext .wpb_wrapper p{
    text-align:center !important;
  }
}

如果您希望将其应用于所有元素,则可以使用

@media only screen and (max-width: 767px) {
  .centertext .wpb_wrapper > * {
    text-align:center !important;
  }
}
相关问题