Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can CSS find an element that has ANY id?

Tags:

html

css

I have a lot of the same elements on a page that is not under my direct control (so i can't change the HTML). This might look like this:

<div class="item">This text should be black</div>
<div class="item" id="brand_one">This text should be red</div>
<div class="item" id="brand_two">This text should be red</div>
...
<div class="item">This text should be black</div>

I want to write a css rule that targets all elements with class item that have an id.

I can do

#brand_one, #brand_two, ... { color:red; }

But the id's go into the hundreds, so that's not an option.

What i'm looking for is a rule something like this:

.item[id] { color:red; } / .item# { color:red; }

I know this is possible in Javascript, but does this exist in CSS?

like image 977
Davy Avatar asked May 19 '15 08:05

Davy


People also ask

How can we select an element with a specific ID in CSS?

The id selector uses the id attribute of an HTML element to select a specific element. The id of an element is unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element.

Does ID use CSS?

ID and class are two of the mostly used CSS selectors that not only help with building the layout of the HTML document but they also help with styling it.

How do I select an element by ID?

In JavaScript, you can almost select any element from the DOM based on its unique ID by using the getElementById() method. It returns the first element that matches the given ID, or null if no matching element was found in the document.

Can multiple elements have same ID CSS?

Answer. As HTML and CSS are designed to be very fault tolerant, most browsers will in fact apply the specified styles to all elements given the same id. However, this is considered bad practice as it defies the W3C spec. Applying the same id to multiple elements is invalid HTML and should be avoided.


2 Answers

Yes, this is possible using CSS attribute selectors:

.item[id] {
    /* any elements with a class .item and an ID attribute */
}
like image 110
feeela Avatar answered Oct 19 '22 11:10

feeela


Yes, this exists. In you case you should use:

div[id*="brand"]  { color: red; }

This selects all divs with an id that contains brand and colors it red.

Edit: You can also, to make sure it only targets ids with brand_ in the start of the id-name, use the following:

div[id^="brand_"] { color: red; }

This will avoid that other divs in the future that have an id that contains brand will also be targeted.

Edit 2: To make it even MORE specific, you can target only ids that are following the class="item":

div[id^="brand_"].item { color: red; }

This targets all divs with brand_ in the beginning of the id and have item as a class.

like image 25
Rvervuurt Avatar answered Oct 19 '22 10:10

Rvervuurt