Use various CSS styles for distinct elements that share a common attribute

Imagine we have two HTML elements, element1 and element2, both created dynamically without IDs:

<element1 class='class1' selected="true" ...[other_attributes]...>
<element1 class='class1' selected="true" ...[other_attributes]...>
<element1 class='class1' selected="false"...[other_attributes]...>
.................................................................
{other <element1> elements}
.................................................................
<element2 class='class2' selected="true" ...[other_attributes]...>
<element2 class='class2' selected="false"...[other_attributes]...>
.................................................................
{other <element2> elements}

The task at hand is to apply different CSS styles based on the 'selected' attribute of each element. For instance, one style for when selected="true" on element1, and another style when selected="true" on element2. This can be achieved using something like:

[selected=true]
{
  color:red;
}

[selected = true]
{
    color:green;
}

The challenge here is to ensure that the correct CSS styling is associated with the respective HTML element.

How can this be accomplished efficiently?

Answer №1

When working with the same element, classes and IDs have specific purposes:

<element id="ID1" class="red" selected="true">
<element id="ID2" class="green" selected="true">

Using IDs:

element#ID1[selected=true]
{
    color:red;
}

element#ID2[selected=true]
{
    color:green;
}

Utilizing classes:

element.red[selected=true]
{
    color:red;
}

element.green[selected=true]
{
    color:green;
}

Remember that IDs must be unique, while classes can be assigned to multiple elements.

Edit: Considering your updated inquiry:

element.class1[selected=true]
{
    color:red;
}

element.class2[selected=true]
{
    color:green;
}

Alternatively, you could differentiate based on their parent elements (if applicable):

parent#ID1 element[selected=true] { ... }
parent#ID2 element[selected=true] { ... }

Answer №2

Try the following:

element1[active="yes"]
              {
  text-decoration: underline;
}

element2[chosen="true"]
             {
color:blue
}

Answer №3

Updated based on your example code changes, I have included my initial response below for comparison

Combine class and attribute selectors in the following way:

HTML

<input class="class1" name="input" />
<input class="class1" />
<input class="class1" name="input" />

<input class="class2" name="input" />
<input class="class2" />

CSS

.class1[name=input]
{
    border: 1px solid red;
}

.class2[name=input]
{
    border: 1px solid green;
}

Initial Response

In CSS3, utilize the :nth-of-type(n) selector as shown below:

HTML

<input name="test" value="First element">

<input name="test" value="Second element">

(Please note that the provided markup above is not recommended for real-life usage!)

CSS

<style>

    [name=test]:nth-of-type(1)
    {
        color: red;
    }

    [name=test]:nth-of-type(2)
    {
        color: green;
    }

</style>

For further information, visit http://www.w3schools.com/cssref/sel_nth-of-type.asp

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

Is there a way to expand this embedded video so that it spans the entire width of the screen

I have a code snippet with one row and two columns. I would like to embed a video from Vimeo in the first column so that it fills the entire column without any padding. Additionally, I want the two columns to be right next to each other with no space betwe ...

Having trouble fitting oversized images into Bootstrap columns, attempting to resize them to stay within the column boundaries

Struggling with a challenge in my CMS - figuring out how to allow users to drag images of any size into a bootstrap column/row and have them responsively scale to fit. The goal is to ensure that these images stay within the designated area between a header ...

Banner with video background (not taking up the entire page)

I'm currently working on a website project that involves using a YouTube video as the banner, but I'm facing some challenges in making it work correctly. So far, this is what I have: #video-background { position: absolute; right: 0; top:1 ...

Which is more effective: coding with just plain JavaScript and CSS, or utilizing frameworks?

As a student, is it more beneficial to focus on utilizing pure JavaScript & CSS or frameworks? And which approach is best suited for the professional field? ...

Django: Hosting CSS on S3 with accurate URL, yet failing to load

My STATIC_URL is configured to point to the URL of my S3 bucket and the static directory within it. STATIC_URL = 'https://s3.amazonaws.com/XXXXXXX/static/' When I try to load the stylesheets in my template using: <link href="{{ STATIC_URL } ...

How can you use JavaScript to retrieve the position of an element on a webpage?

As mentioned in the title, I am looking for a way to retrieve the x and y positions of an element relative to its location on the webpage and based on its positioning schemes such as absolute or relative. ...

Angular functions are executed twice upon being invoked within the html file

I decided to kick-start an Angular project, and I began by creating a simple component. However, I encountered a perplexing issue. Every time I call a function in the HTML file from the TypeScript file, it runs twice. TS: import { Component, OnInit } from ...

I am having trouble adjusting my web page to fit the screen fluidly as it appears too large and requires horizontal scrolling

As a student learning html/css, I am currently facing some challenges with my first website. My main issue is setting up the page to be fluid rather than fixed. The box, image, and text are all configured to be absolute on the page, but I cannot seem to ma ...

Adjust the width of the TinyMCE Editor to automatically resize based on the content being

Is it possible for TinyMCE to adjust the content within an absolutely positioned container and update the width while editing? <div class="container"> <textarea>This is my very long text that should not break. This is my very long text tha ...

What is the best way to position a form element, such as a search bar, in the center of a navigation

<nav class="navbar navbar-light bg-light"> <a class="navbar-brand" href="#"> <img src="/images/logo.svg" width="30" height="30" class="d-inline-block align-top" alt="">Cool Brand</a> <div class="d-flex justify-content-cen ...

Styling with Radial Gradients in CSS

Struggling to create a banner with a radial gradient background? I'm almost there, but my code isn't matching the design. Any assistance would be greatly appreciated as I can't seem to get the right colors and only part of the first circle i ...

What could be causing a hydration error when utilizing a table in Next.js?

When attempting to use the tr tag in my code, I encountered an error message that reads: Unhandled Runtime Error Error: Hydration failed because the initial UI does not match what was rendered on the server. import React from 'react' import {useS ...

The elegant-admin template's mobile navigation toggle is missing

I recently downloaded an admin theme and added the CSS to my Django static files. However, after doing so, the mobile toggle feature disappeared. I double-checked all the CSS and JS links in the index template, and they are correctly linked to the paths, b ...

When I click the button, I would like the value of the button to be displayed in a textbox

I'm currently working on an interactive virtual keyboard project and need help with a function that will display the pressed button values in a text box located next to the keyboard. Here is the code snippet I've come up with so far: <script ...

Troubleshooting PHP code: resolving issues with images not appearing in forwarded emails

Currently, I am utilizing HTML email templates to send emails with images. However, when I forward the email to another recipient, the HTML template format gets disrupted. My method of using HTML templates is as follows - $message = file_get_contents(&apo ...

Adding data into a JSON Array

I'm attempting to add values from an input textbox into a JSON array. Here's my current approach: Code: <!DOCTYPE html> <html> <body> <input id="studentnumber" placeholder="Student Number"></input> <input id="s ...

Easily manipulate textboxes by dynamically adding or deleting them and then sending the data to a

Can you provide a simple example of how to dynamically add and remove textboxes and then display the results? I envision it like this: [Empty Textbox][Add button] When 'Value1' is entered into the textbox and 'add' is clicked, it s ...

The scrollbar remains visible on mobile devices

I'm attempting to remove the scrollbar from all elements in my Vue + Vite application. I do not want to disable scrolling, just hide the scrollbar itself. To achieve this, I have employed the following code snippet. *::-webkit-scrollbar { display: ...

Ensure that the child iframe is referencing its own content, and not that of the parent iframe

What I have is a nested Iframe setup as shown below <iframe id="is Static"> stuff <iframe id="Is Dynmic> <html>...</html> <body id="This is thebody"> other stuff </body> I am trying to listen for the mou ...

Is CSS Transition smoothly easing in, but not out?

On the image gallery of this website , I have applied transitions to the images, where they ease in (fade in), but revert back to their original state instantly when the mouse moves off the image. Is there a way to make the transition reverse when the mo ...