I have some code that I think may be bulky and could be simplified. I haven't found anything that helps in my situation. I am trying to make it so that when I hover over a div
, an h2
and p
get underlined. It works fine like this:
.test:hover h2, .test:hover p {
text-decoration: underline;
}
But I was wondering if I could simplify it in some way, not having to repeat .test:hover
twice.
CodePudding user response:
There is a new pseudo-class :is
which will allow this..
The
:is()
CSS pseudo-class function takes a selector list as its argument, and selects any element that can be selected by one of the selectors in that list.
.test:hover :is(h2, p) {
color: red;
text-decoration: underline;
}
<div >
<h2>Heading</h2>
</div>
<div >
<p>Lorem ipsum dolor sit amet.</p>
</div>
CodePudding user response:
If you don't need to support Internet Explorer this can be accomplished with the :is
pseudo-class:
.test:hover :is(h2, p) {
text-decoration: underline;
}
<div >
<h1>An H1</h1>
<h2>An H2</h2>
<p>A paragraph</p>
</div>
An alternative would be to leverage a CSS preprocessor like Sass or Less, both of which support nesting which can make for DRY-er, more expressive style source code. This may be overkill in your case, though. Here's an example in Sass' SCSS
format:
.test:hover {
h2, p {
text-decoration: underline;
}
}
CodePudding user response:
You can use it:
:is(h1, p) .test:hover {
text-decoration: underline;
}