Add CSS properties to child elements that are not of a specific selector, while styling their descendants without any restrictions

Seeking assistance for an Angular application, but the query also pertains to CSS principles in general.

In my Angular project, I have a main component containing several child components, all with standard view encapsulation. Specifically, I am looking to adjust the line-height of all p tags within the parent and child components to a different value.

I have found a solution using SCSS as shown below:

:host {
    ::ng-deep {
        p {
            line-height: 2em;
        }
    }
}

However, I wish to exclude a specific child component - let's name it foobar. My attempt is demonstrated here:

:host {
    ::ng-deep {
        :not(foobar) {
            p {
                line-height: 2em;
            }
        }
    }
}

It appears this does not work as expected due to other elements possibly containing the p tag as descendants.

An alternative approach could be:

:host {
    ::ng-deep {
        p:not(foobar p) {
            line-height: 2em;
        }    
    }
}

Nevertheless, managing multiple overrides for various elements or classes can become cumbersome with this method.


Hence, my question remains; is there a more efficient or modern way to achieve this using SCSS or updated selectors? Are there any Angular features that could assist in this scenario (aside from disabling viewEncapsulation)?

Answer №1

If you're looking to deeply customize the styles of the parent component and its child components, you can achieve this by creating a separate stylesheet and including it in the parent's styles array as shown below:

Parent Component

<p>Parent paragraph</p>
<child-one></child-one>
<child-two></child-two>

Child One

<p>Child one paragraph</p>

Child Two

<p>Child two paragraph</p>

extra-styles.scss

:ng-deep {
  child-one {
    p {
      color: green;
    }
  }

  child-two {
    p {
      color: blue;
    }
  }
}

parent.styles.scss

p {
  color: cyan;
}

parent.component.ts

@Component({
  selector: 'parent',
  template: './parent.html',
  styles: ['./parent.styles.scss', 'extra-styles.scss']
})
export class ParentComponent {}

Check out the Demo

Answer №2

To solve this issue, I implemented a SCSS mixin:

@mixin not-foobar {
    &:not(foobar #{nth(nth(&, 1), length(nth(&, 1)))}) {
        @content;
    }
}

Here's how you can use it:

:host {
    ::ng-deep {
        p {
            @include not-foobar {
                line-height: 2em;
            }
        }    
    }
}

This mixin allows me to generate the p:not(foobar p) { selector only where necessary, avoiding potential errors from manually setting the selector.

The

#{nth(nth(&, 1), length(nth(&, 1)))})
part of the mixin specifically targets the immediate parent element. Using just & would select the entire parent, causing unintended consequences in my situation.

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

Tips for implementing fluid transitions between mouse X and Y coordinates using JavaScript

I recently developed a function that enables a DOM element to follow the mouse cursor. You can check out the code here. Currently, I am looking for suggestions on how to add a nice animation to this feature. Ideally, I want to incorporate a slight delay w ...

Incorporating @angular/fire into the latest version of Angular, version

I need help incorporating @angular/fire into my Angular 12 project for deployment on Firebase. After using the CLI to add @angular/fire, I ran the following command: ng add @angular/fire The output displayed was as follows: ℹ Using package manager: npm ...

The Firestore query for viewing resources is currently not functioning as expected due to issues with

I'm currently working on implementing the "read" Rules from an array, following the guidelines in this blog post var db = firebase.firestore(); db.collection("_users").where("viewers", "array-contains", myUID) .get() .then((querySnapshot ...

Can anyone provide guidance on how to create this particular shadow effect using CSS?

Is there a method to use CSS to create a green shadow in that particular shape? ...

What is the process for calculating a class property in typescript?

If I were writing this in JavaScript, it would look like: function a(b,c) {this.foo = b; this.bar = c; this.yep = b+c} // undefined b = new a(1,2) // a {foo: 1, bar: 2, yep: 3} However, I've been struggling to achieve the same in TypeScript. None of ...

Utilizing the most recent HTTP response from the previous request in Angular 8

Currently working with angular 8 and facing an issue on my list page with filters. Whenever a filter value is changed, it triggers an http request. The problem arises when users start changing the filters too frequently, causing multiple api requests to be ...

Angular 9 library compilation issue: Module unused warning detected

After upgrading my project from Angular 8 to Angular 9, I encountered a warning when trying to build the library: The '__read' is imported from external module 'tslib', but never used https://i.stack.imgur.com/Xg4Eu.png This warning ...

What impact does switching from HTML input to form_for in Rails have on the structure of the code?

Recently, I made some adjustments to the website I've been working on. Initially, it was created using HTML, CSS, and Javascript. There was a section for email subscriptions which originally only had an HTML input field. However, as we started develop ...

When trying to create a new project using `ng new project`, the path specified was not

I'm attempting to start an angular 4 project using angular-cli on my Windows 10 operating system. I followed the instructions outlined at https://www.npmjs.com/package/@angular/cli. Currently, I am running node - 7.6.0 and npm - 5.1.0. Every time I ...

Clicking on a different texture/image allows for the texture to change in Three.js

I am working on creating a 360 image view using Threejs. I have a total of 4 images, with one linked to Threejs and the other 3 displayed as thumbnails at the bottom of the page. When a thumbnail is clicked, the 360 image view should change accordingly. Y ...

Using CSS to position a pair of divs containing text and images side by side

Is there a better approach to creating two divs and two pictures without using negative margins, similar to the example shown here? ...

Manipulate div display based on select value in Angular2 using [(ngModel)] with ion-select

I am currently working with ionic2 and angular2 using JavaScript, not TypeScript. I have two inputs: one for text and the other a select dropdown. My goal is to hide the text input if the value selected in the dropdown is 'more'. How can I achiev ...

Extracting information from Timeless-time-picker utilizing form control

<timeless-time-picker [hourFormat]="'hours24'" [visibleItemsCount]="3" [size]="'medium'" [theme]="'dark'" [selectionHighlightStyle]="'none'" [selectionBoxBackgro ...

``Are there any thoughts on how to troubleshoot display problems specifically on mobile

Whenever I use Safari on iOS for my web application, I encounter strange rendering issues. It's odd because the majority of the time everything functions as it should, but every now and then these bugs crop up with no discernible pattern. Examples th ...

Minimization tools for compressing CSS and JavaScript documents

After deploying my application, I noticed that the loading time has significantly increased. Is there a way to compress CSS and JS files? I include only the necessary code in each page and occasionally use minified versions of JS. Thank you. ...

The beginning of an HTML document and the viewport (screen view) location

Absolute positioning is relative to a containing block that provides a positioning context, which defaults to the document. a) If absolute positioning is relative to the document, can we visualize the starting point of a document as a two-dimensional coor ...

What is the best way to prevent images from being loaded with broken links?

Currently, I am working on a new feature that involves rendering images from servers. In the process of aligning these images, I noticed an excessive amount of white space due to loading images with broken links. https://i.stack.imgur.com/jO8BR.png Here ...

Discover how to capture and process POST form data in Angular originated from external sources

I am currently building a website that utilizes Java for the backend and Angular for the frontend. I have encountered a scenario where external websites may transmit data to my site via POST form submissions. For example, ▼ General    & ...

Replace the service provided by NgModule within a web component

My angular library exports its components as web components. Below is a snippet from my app.module.ts: import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule } from '@angular/common/http'; import { Injecto ...

Issues with animations in Ionic 3 and Angular 4 not functioning as expected

Working on a component to animate an accordion list, I made all the necessary changes such as importing import { BrowserModule } from "@angular/platform-browser"; and import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; as well ...