是否可以编写css规则来选择和设置具有非空类属性的所有元素?
假设我有2个不同的段落或标题与不同的类。例如,h1具有“id1”类,而h2具有“id2”类。 我怎样才能给它们打造两种风格?
谢谢。
答案 0 :(得分:4)
你可以使用:
.id1, .id2{
//your css here
}
或者,如果您的所有元素都具有class
属性,那么您可以使用:
*[class]{
//your css
}
但是,上面也选择了空class
的元素,例如:
<h1 class></h1>
或
<h1 class=""></h1>
要排除此类例外,您可以将选择器修改为:
*[class]:not([class=""])
答案 1 :(得分:2)
您可以使用如下属性选择器:
[class] {
color: red;
}
<p class="a">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quod quam praesentium alias recusandae tempora perspiciatis molestias accusamus ad in fuga, officiis id voluptate, quasi, rem inventore, illum sint voluptatem. Dolor.</p>
<p class="b">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quod quam praesentium alias recusandae tempora perspiciatis molestias accusamus ad in fuga, officiis id voluptate, quasi, rem inventore, illum sint voluptatem. Dolor.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quod quam praesentium alias recusandae tempora perspiciatis molestias accusamus ad in fuga, officiis id voluptate, quasi, rem inventore, illum sint voluptatem. Dolor.</p>
h1[class] {
color: blue;
}
<h1 class="a">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quod quam praesentium alias recusandae tempora perspiciatis molestias accusamus ad in fuga, officiis id voluptate, quasi, rem inventore, illum sint voluptatem. Dolor.</p>
<h1 class="b">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quod quam praesentium alias recusandae tempora perspiciatis molestias accusamus ad in fuga, officiis id voluptate, quasi, rem inventore, illum sint voluptatem. Dolor.</p>
<h2 class="c">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quod quam praesentium alias recusandae tempora perspiciatis molestias accusamus ad in fuga, officiis id voluptate, quasi, rem inventore, illum sint voluptatem. Dolor.</p>