Home > Software design >  use :has to take two element in attribute
use :has to take two element in attribute

Time:10-08

I have this HTML code:

<button >
  <icon></icon>
  <span><span>
</button>

I need to separate icon and span only when the button has two children, something like this in CSS:

.mod:has( icon, span) {
  padding-left: 1px;
}

But it doesn't work. Anyone can help me?

CodePudding user response:

You can use direct child combinator (>) plus
:first-child pseudo-class plus
sibling combinator ( )

.container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  row-gap: 1rem;
}

button {
  display: block;
}

.btn:has(> :first-child   *) {
  padding-left: 2rem;
}
<div >
    <button >
        <span>1</span>
        <span>2</span>
    </button>

    <button >
        <span>1</span>
    </button>
</div>

CodePudding user response:

You can chain multiple :has() selectors: .mod:has(icon):has(span)

Here's a working example:

.mod {
  border: 0;
  background-color: #CCC;
  padding: 10px 20px;
  border-radius: 5px;
}

.mod:has(icon):has(span) {
  padding-left: 1px;
  background-color: #C00;
  color: #FFF;
}
<button >Lorem</button>
<button >  
  Ipsum
  <icon></icon>
  <span></span>
</button>
<button >Dolor</button>

Note that, as pointed out by @MisterJojo in the comments below, the :has() selector does not yet have full support amongst all major browsers. You can check which browsers do support it here, to validate that it covers your required user base.

  • Related