Control the transparency of the initial parent div that includes an *ngFor loop

I want to add opacity only to the first div which contains an icon and a heading in another nested div. The second div should remain fully visible (opacity: 1).

Here is the HTML structure:

<div class="row clearfix">
    <div class="col-lg-3 col-md-6 col-sm-12 mb-30 parent" (click)="click(item)" *ngFor="let item of services">
      <div class="pd-30 bg-secondary border-radius-4 box-shadow text-center height-100-p child">
        <div style="margin-top: 30px">
          <i class="{{item.icon_class}}" style="font-size:40px;" aria-hidden="true"></i>
        </div>
        <h5 class="pt-20 mb-30" style="white-space: normal;">{{item.title}}</h5>
      </div>
    </div>
</div>

CSS Style:

.parent{
    opacity: 0.3;
}

.child{
    background-color:rgba(0,0,0,1);
}

The current layout can be viewed here.

I've searched online for solutions but found examples that involve closing the first div, which is not feasible due to the presence of *ngFor loop.

Any suggestions on how to achieve this effect?

In addition, there will be a need to implement a feature allowing users to control the opacity percentage as different users may have varying backgrounds where adjustment might be necessary.

Thank you for your help!

Answer №1

Here are a few different approaches:

  • One option is to utilize the *ngFor directive:

    <div class="col-lg-3 col-md-6 col-sm-12 mb-30" (click)="onClick(item)" *ngFor="let item of services; let isFirst = first">
      <div class="pd-30 bg-secondary border-radius-4 box-shadow text-center height-100-p child" [class.parent]="isFirst">
    
  • Another solution is to apply CSS using the selector :first-child:

    parent div:first-child {
      opacity: 0.3;
    }
    

Answer №2

To target the first child of a parent element in CSS, you can apply the :first-child selector to the .parent class.

Answer №3

  • Utilize ngClass to apply a class to the div based on a condition

<div class="row clearfix">
  <div [ngClass]="{'parent':idx==0}" class="col-lg-3 col-md-6 col-sm-12 mb-30" (click)="click(item)" *ngFor="let item of services;let idx = index">
    <div class="pd-30 bg-secondary border-radius-4 box-shadow text-center height-100-p child">
      <div style="margin-top: 30px">
        <i class="{{item.icon_class}}" style="font-size:40px;" aria-hidden="true"></i>
      </div>
      <h5 class="pt-20 mb-30" style="white-space: normal;">{{item.title}}</h5>
    </div>
  </div>
</div>

  • Alternatively, you can use the first child CSS selector:

<div class="row clearfix">
    <div class="col-lg-3 col-md-6 col-sm-12 mb-30 parent" (click)="click(item)" *ngFor="let item of services">
      <div class="pd-30 bg-secondary border-radius-4 box-shadow text-center height-100-p child">
        <div style="margin-top: 30px">
          <i class="{{item.icon_class}}" style="font-size:40px;" aria-hidden="true"></i>
        </div>
        <h5 class="pt-20 mb-30" style="white-space: normal;">{{item.title}}</h5>
      </div>
    </div>
</div>

css :

parent:first-child {
  opacity: 0.3;
}


  • If you want the user to control the opacity percentage, create a TS variable representing the opacity and use it with ngStyle Example :

opacity=0.3;

HTML :

<div class="row clearfix">
  <div [ngStyle]="{'opacity':idx==1 ? opacity : 1}" class="col-lg-3 col-md-6 col-sm-12 mb-30" (click)="click(item)" *ngFor="let item of services;let idx = index">
    <div class="pd-30 bg-secondary border-radius-4 box-shadow text-center height-100-p child">
      <div style="margin-top: 30px">
        <i class="{{item.icon_class}}" style="font-size:40px;" aria-hidden="true"></i>
      </div>
      <h5 class="pt-20 mb-30" style="white-space: normal;">{{item.title}}</h5>
    </div>
  </div>
</div>

{opacity':idx==1 ? opacity : 1} means set the opacity to value of opacity if it's the first element, otherwise set it to 1

Give the user the ability to manage the TS variable

Answer №4

Each object in the services array can have one property which is used in every iteration to determine the style or class to apply

    <div class="row clearfix">
        <div class="col-lg-3 col-md-6 col-sm-12 mb-30 parent" (click)="click(item)" *ngFor="let item of services">
          <div class="pd-30 bg-secondary border-radius-4 box-shadow text-center height-100-p child" [ngClass]="item.isFirstChild ? 'apply-opacity' : ''">
            <div style="margin-top: 30px">
             <i class="{{item.icon_class}}" style="font-size:40px;" aria-hidden="true"></i>
        </div>
        <h5 class="pt-20 mb-30" style="white-space: normal;">{{item.title}}</h5>
      </div>
    </div>
</div>

Answer №5

Apologies for the delay and gratitude to all who provided answers!

After trying various approaches without success, I ultimately found a solution (in my opinion) by optimizing the code. Employing 'rgba' proved successful.

To achieve different opacity levels, I created multiple CSS classes:

 /* opacity_level */
.opacity20 {
  background: rgba(255,255,255,0.2) !important;
}
.opacity30 {
  background: rgba(255,255,255,0.3) !important;
}
.opacity40 {
  background: rgba(255,255,255,0.4) !important;
}
.opacity50 {
  background: rgba(255,255,255,0.5) !important;
}
.opacity60 {
  background: rgba(255,255,255,0.6) !important;
}
.opacity70 {
  background: rgba(255,255,255,0.7) !important;
}
.opacity80 {
  background: rgba(255,255,255,0.8) !important;
}
.opacity90 {
  background: rgba(255,255,255,0.9) !important;
}
.opacity100 {
  background: rgba(255,255,255,1) !important;
}

I then set up a variable named OpacitiyClass, which will store the selected CSS class name that users pick from the settings page:

opacityClass: string = configuration.opacity_class;

This value is passed directly in HTML as follows:

      <div class="row clearfix">
        <div class="col-lg-3 col-md-6 col-sm-12 mb-30" (click)="click(item)"
                *ngFor="let item of services">
          <div class="pd-30 {{opacityClass}} border-radius-4 box-shadow text-center height-100-p">
            <i class="{{item.icon_class}}" style="font-size:40px;" aria-hidden="true"></i>
            <h5 class="pt-20 mb-30" style="white-space: normal;">{{item.title}}</h5>
          </div>
        </div>
      </div>

I hope this explanation proves useful to someone out there!

Once again, thank you to everyone for your contributions!

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

Testing the selection of dropdown values in Angular2 using unit tests

I have a dropdown menu for selecting countries. It defaults to a pre-selected value, and when the user changes it, they are redirected to the corresponding country page. However, I am facing an issue while trying to unit test the default value in the sele ...

The proper approach is using CSS for linking pseudo-classes

Look what I stumbled upon: Important: Remember, a:hover MUST be placed after a:link and a:visited in the CSS code to work properly!! Remember: Place a:active after a:hover for it to have an effect in the CSS code!! Note: Pseudo-class names are not case- ...

Adjust the HTML 5 range slider to update according to the selected value

Is it possible to create a custom marker on an HTML5 range input element? I'm looking for a way to change the design of the circle marker as it moves along the scale from 1 to 10. Specifically, I want to change the color of the marker based on its po ...

How can I prevent the installation of my Ionic 2 application on devices that have been rooted or jailbroken?

I am currently working on a project involving an Ionic 2 and Angular 2 application. I need to implement a feature that checks whether the device is rooted (in the case of Android) or jailbroken (in the case of iOS). I have experimented with various packag ...

techniques for accessing HTML source code through an AJAX call

I am trying to retrieve the HTML source of a specific URL using an AJAX call, Here is what I have so far: url: "http://google.com", type: "GET", dataType: "jsonp", context: document.doctype }).done(function ...

Can a Unicode character be overwritten using a specific method?

Is there a way to display a number on top of the unicode character '♤' without using images? I have over 200 ♤ symbols each with a unique number, and using images would take up too much space. The characters will need to be different sizes, a ...

Combining TypeScript into HTML resulted in an error: Uncaught ReferenceError clickbutton is not defined

Attempting to create a basic CRUD frontend without the use of any frameworks. I am encountering an issue when trying to include a TypeScript file (index.ts) in my index.html, as the functions called within it are showing as undefined. I understand that bro ...

Tips for defining data types for spreading properties in TypeScript

I'm grappling with adapting this code to function properly in TypeScript type ScrollProps = { autoHide: boolean autoHideTimeout: number autoHideDuration: number } const renderThumb = ({ style, ...props}) => { const thumbStyle = { borde ...

Implementing Form Validation in Angular 5 and showing errors in a reusable component

My current setup includes a generic component structured as follows: // selector: 'app-text-box' <form> <input type="text" [name]="data.name" [id]="data.name"/> </form> <error-message [message]="message"></ ...

Limit access to Google Fusion Table to specific types of maps. Eliminate Google Fusion Table for selected map formats

Currently, I am in the process of creating a web map using the Google Maps Javascript API. My objective is to display a Google Fusion Table containing buildings in Boston exclusively on a stylized map named "Buildings." When I switch to the Buildings map t ...

What is the best way to format text for a copy to clipboard function while using Jasmine?

I've developed a directive for copying content to the clipboard. Here is the code: import { Directive, Input, Output, EventEmitter, HostListener } from '@angular/core'; @Directive({ selector: '[copyClipboard ...

Issue with bottom margin on the last flex item located at the end of the container is not being applied

My button is currently touching the end of the container, but I want to create some space between them. However, adding a margin bottom to the button does not seem to be working as expected. Below is the CSS and HTML code: .events{ height: 100%; d ...

Could we bypass the parent component somehow?

Just starting out with angular and decided to work on a small project. As I was setting up my routing, I encountered a problem. Here is the routing setup I have: const routes: Routes = [ {path: '', redirectTo: '/home', pathMatch: &a ...

Difficulty with spacing in HTML/CSS styling

Here is what I'm currently working on: link to jsfiddle code * { margin: 0; padding: 0; } html { height: 100%; } header, nav, section, article, aside, footer { display: block; } body { font: 12px/18px Arial, Tahoma, Verdana, sans- ...

Adjust the color of the paper in Material-UI

I'm in the process of creating a React project using the material-ui library. Currently, I am facing an issue with customizing the drawer component's background color. After some research, I learned that modifying the paper attribute of the drawe ...

Is there a way to merge two typed Joi schemas together?

I have two different interfaces, where the second one is an extension of the first: interface Core { id: string; } interface User extends Core { firstName: string; } To ensure validation, I utilize Joi schemas. For the Core interface, it's easy ...

Module '@types/mongodb' could not be located

Currently, I am working on a Node.js application using Typescript with a MongoDb database. Unfortunately, I encountered an issue today related to importing the type definitions of MongoDb. When I try to import the Db type like this: import { Db } from "@ ...

Converting JSON into an interface in TypeScript and verifying its validity

How can I convert a JSON string to a nested interface type and validate it? Although my model is more complex, here is an example: export interface User = { name: Field; surname: Field; }; export interface Field = { icon: string; text: string; vis ...

What is the best way to transpile TypeScript within the Astro framework?

Recently, I decided to dive into exploring Astro for a couple of upcoming projects. In my research, I delved into the script and typescript sections of the documentation (), as well as (). However, I found the workflow somewhat counterintuitive and struggl ...

Exploring the communication between two components in Angular 2

My Angular components include: Create-Articles: used for creating articles. List Articles: utilized for listing all articles. The parent component is the Home Component. import { Component, OnInit } from '@angular/core'; @Component({ ...