skip to Main Content

Consider this snippet:

.wrapper {
  display: flex;
  gap: 5px;
  border: 1px solid black;
  border-radius: 3px;
  width: 80px;
  padding: 5px;
}
<div class="wrapper">
  <div class="icon">🖼️</div>
  <div class="text">paintings</div>
</div>

The icon may or may not be present.

What I’m trying to achieve is that, if the icon is not present, some left padding is added to .text.

How do I do that? I tried a few combinations of :has, :not and + (the next-sibling combinator), to no avail.

Essentially, I want to select .text, but only if it is not preceded by .icon.

2

Answers


  1. .wrapper:not(:has(div.icon)) div.text
    should do it.

    Example 1 (with icon)

    .wrapper {
      display: flex;
      gap: 5px;
      border: 1px solid black;
      border-radius: 3px;
      width: 80px;
      padding: 5px;
    }
    
    .wrapper:not(:has(div.icon)) div.text {
      padding-left: 40px;
    }
    <div class="wrapper">
      <div class="icon">🖼️</div>
      <div class="text">paintings</div>
    </div>

    Example 2 (without icon)

    .wrapper {
      display: flex;
      gap: 5px;
      border: 1px solid black;
      border-radius: 3px;
      width: 80px;
      padding: 5px;
    }
    
    .wrapper:not(:has(div.icon)) div.text {
      padding-left: 40px;
    }
    <div class="wrapper">
      <div class="text">paintings</div>
    </div>
    Login or Signup to reply.
  2. .text:not(.icon + .text) should do the trick

    .wrapper {
      display: flex;
      gap: 5px;
      border: 1px solid black;
      border-radius: 3px;
      width: 80px;
      padding: 5px;
    }
    
    .text:not(.icon + .text) {
      padding-left: 24px;
    }
    <div class="wrapper">
      <div class="icon">🖼️</div>
      <div class="text">paintings</div>
    </div>
    
    <div class="wrapper">
      <div class="text">paintings</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search