Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get CSS to select ID that begins with a string (not in Javascript)?

People also ask

How do I select a specific ID in CSS?

The CSS id Selector 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.

Can CSS id start with a number?

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit.

Can we use * in CSS?

The asterisk (*) is known as the CSS universal selectors. It can be used to select any and all types of elements in an HTML page. The asterisk can also be followed by a selector while using to select a child object. This selector is useful when we want to select all the elements on the page.

What is the prefix for a CSS ID selector?

The #id selector allows you to target an element by referencing the id HTML attribute. Similar to how class attributes are denoted in CSS with a “period” ( . ) before the class name, ID attributes are prefixed with an “octothorpe” ( # ), more commonly known as a “hash” or “pound sign”.


[id^=product]

^= indicates "starts with". Conversely, $= indicates "ends with".

The symbols are actually borrowed from Regex syntax, where ^ and $ mean "start of string" and "end of string" respectively.

See the specs for full information.


I'd do it like this:

[id^="product"] {
  ...
}

Ideally, use a class. This is what classes are for:

<div id="product176" class="product"></div>
<div id="product177" class="product"></div>
<div id="product178" class="product"></div>

And now the selector becomes:

.product {
  ...
}

Use the attribute selector

[id^=product]{property:value}

I want to share this solution too, maybe in the future it could help someone.
As the others said you can write [id^=product] for id

But we can give an example for the class as well: [class^="product-"] which indicates classes starts with product and also * like this [class*="product-"]

This is a simple example :

/* Icons */
[class^="icon-"], [class*=" icon-"] {
  /* use !important to prevent issues with browser extensions that change fonts */
  font-family: 'mk-font' !important;
  font-size: 3em;
}

good luck ...