Using the ampersand in Sass conditionals

I have some specific styling defined like this

.activities {
  border: 1px solid green;

  .activity {
    background-color: red;

    &:first-child {
      background-color: yellow;
    }
  }  
}

I am looking to style the .activity element that is a first child with a yellow background, only if the parent element with .activities class does not have the additional class .events.

In the scenario below, the first .activity element should maintain a background-color: red

<div class="activities events">
  <div class="activity">one</div>
  <div class="activity">two</div>
  <div class="activity">three</div>
</div>

Are there alternative methods to exclude this first-child styling when the element with class .activities also contains the class .events?

or is this the most straightforward solution:

.events .activity:first-child {
  background-color: red;
}

Answer №1

Implement the :not selector to set a yellow background for the activities element when it does not contain the events class.

.activities {
    border: 1px solid green;

    .activity {
        background-color: red;
    }

    &:not(.events) {
        .activity:first-child {
            background-color: yellow;
        }
    }  
}

This technique reduces redundancy in your code. If you decide to change the color of activity from red to blue, you only need to make the adjustment in one place instead of multiple locations.

https://developer.mozilla.org/en/docs/Web/CSS/:not

Answer №2

I was feeling uninspired and decided to challenge myself by containing all the activity styles within a single nested activity element. The result is this code snippet - although I would advise against using it instead of Nathan's solution, as it seems unnecessarily complex:

.activities {
  border: 1px solid green;

  .activity {
    background-color: red;

    &:first-child {
      @at-root #{selector-replace(&, '.activities', '.activities:not(.events)')} {
        background-color: yellow;
      }
    }
  }
}

If you want to avoid repeating the 'activities' class, you could store it as a variable:

.activities {
  $this: &;

  border: 1px solid green;

  .activity {
    background-color: red;

    &:first-child {
      @at-root #{selector-replace(&, $this, '#{$this}:not(.events)')} {
        background-color: yellow;
      }
    }
  }
}

Is Sass pushing the boundaries too far?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to align my navigation bar in the middle of two elements with different

I've been struggling with my code for the past couple of days, but nothing seems to be working. I need the navigation bar to be perfectly centered between two elements (<img> and <form>). Right now, it's almost centered, but it starts ...

The position of the scroll bar remains consistent as you navigate between different websites

Is it possible for me to click on a link within my HTML website and have the other website load with me in the exact same position? For example, if I'm halfway down a webpage and click a link, can I be taken to that same point on the new page? If so, ...

"When the screen resolution changes, the absolute positioning of images won't function as expected

I am trying to overlay one image on top of another background image, but I am facing an issue. When I change the screen resolution, the position of the image that should be placed over the background image also changes. Below is the code I am using: ...

Missing ng-required fields not displaying the has-error validation in AngularJS forms

While editing any part of their address, the user should see a red invalid border around each field to indicate that the full form is required. However, for some reason I can't seem to get the 'Address' field to display this border. The set ...

Tips for eliminating excess space on mobile devices with CSS

When testing the responsiveness of my banner image at a specific breakpoint, I noticed white space. You can see the issue on my website here. https://i.sstatic.net/Oug2R.png I have tried the following CSS: html, body { width: 100%; -webkit-box-s ...

What is the best way to locate the final text node within the <p> element?

Looking at the code below, my goal is to identify and retrieve the text node that serves as the last child element. <p class="western" style="margin-bottom: 0.14in"> <font color="#000000"> <font face="Arial, serif"> <font ...

Nav bar taking up full width of page, centered to the right with content area

I am facing an issue with aligning my full-width navbar with my fixed content area. The ul keeps changing based on the browser or resolution. Check out this fiddle for reference: http://jsfiddle.net/fwyNy/ subject site CSS Code: #topribbon{ width: 10 ...

What is the reason for the additional space and irregular alignment of my divs when utilizing the 960 grid system?

One issue I'm facing is that elements within divs are aligning randomly without responding to any alignment tags. Additionally, some divs are creating extra space above or below their elements. I am using the 960 grid system and have not made any chan ...

Creating flexible padding for child elements inside a container using CSS

I am facing a challenge in creating dynamic padding within a container. Consider the following HTML: <div class="sections-container"> <div class="section"> </div> <div class="section"> </div> </div> and the corres ...

Create a user interface design for displaying alerts on a web

Currently, I am in the process of creating a form that includes a text box. One important validation I need to implement is that the name entered must be unique. My approach involves accessing the parent div and modifying the entire HTML content within it ...

Switch the class of a div using jQuery when it is clicked

I need to implement functionality where 4 different links change the class of a specific div when clicked. For example, clicking on link 1 will change the class to s1, link 2 to s2, and so on. Below is some code that I have been working on, however, I am ...

Customize the layout of menu icon in HTML/CSS using FlexBox Grid

Recently, I have encountered an issue with the position of a menu icon on my website. The icon is displayed when the window reaches a certain size, but it is not aligned properly on the right side of the site. Ideally, I would like to use the "right" prope ...

I'm encountering problems when attempting to display the image/png response from an xmlHTTPRequest. Instead of the correct data, I

I have implemented the following code to integrate a captcha generating web service. The response data is successfully obtained, but when I attempt to display the result within a div element, the image appears as distorted text. var xmlHttp = new XMLHtt ...

In Outlook, images are always shown in their true dimensions

While everything is working perfectly fine in Gmail, Yahoo, and Hotmail, there seems to be an issue with the display of the logo image on Outlook. The custom width and height settings are not being applied properly, resulting in the logo being displayed ...

"Utilizing ng class with an array of objects: A step-by-step guide

I am facing a scenario in which my response appears as follows: "currency" : [ { "_id" : ObjectId("584aad5d3e2537613e5f4c39"), "name" : "USD" } ], I need to enable my checkbox based on the currency name. I attempted the followi ...

Activating a div in React.js using setActive: Step-by-step guide

Currently, I am in the process of developing an application with three menu tabs, each represented by an accordion comprising a menu title and content. The issue I am facing is that when clicking on any menu title, all content divs are displayed simultaneo ...

Clickable link remains functional after being hidden

Even though I have hidden the Games-div using the .hide() function in jQuery, my links are still clickable. Is there a way to make them unclickable after being hidden? Here is the link to my code on jsFiddle: http://jsfiddle.net/hypertje/Frv8G/ Note: The ...

Ways to incorporate a dictionary into your website's content

I am in the process of developing a website for educational purposes while also honing my web programming skills. On this website, I have encountered some complicated terms that may be difficult for users to understand, so I want to implement a tooltip/mod ...

Implementing Bootstrap 4 accordions within a Knockout foreach loop, adjusting the icon upon expansion/collapse dilemma

I have a collection of collapsible sections within a main collapsible section like: <div id="parentAccordion" class="card-accordion"> <div class="card"> <div class="card-header bg-black text-white pointer-cursor"> ...

How to extract hover CSS property from a Selenium WebElement using XPath in Python

Is there a way to detect if a button changes its background color on hover? I know how to get the cursor property: print webElement.value_of_css_property('cursor') But I am unsure how to capture the hover property. ...