Alvaro
Alvaro

Reputation: 9662

Assign type selector after class name in CSS

Is it possible to add the HTML element selector after the class name?

So instead of:

a.class {color: pink;}

the other way round:

.class?a {color: pink;}

Upvotes: 1

Views: 1221

Answers (3)

pol
pol

Reputation: 2701

The CSS syntax dictates that first comes the element and then other identifiers (id, classes, attributes).
However, there is a way to write it in reverse notation, but the CSS will be longer.

  1. The matching selector:
    For Firefox 4+ :-moz-any(selector1, selector2, etc)
    For Chrome 15+, Safari 5+, Opera 15+ :-webkit-any()
    IE/Edge have no support.
    The new specification would be: :matches(), which isn't supported by any browser yet.

    Selectors Level 4 specification
    MDN docs


  1. Using negation :not():
    With this, you can choose element to ignore
    :not(div)
    To ignore multiple elements, you will need to use :not multiple times:
    :not(div):not(span)


Check this demo:

.one { background-color: green; }
.two { background-color: blue; }

/*The matching selector must be written separately for each vendor*/
/*If we use comma, the whole rule is ignored by the browser*/
.one:-moz-any(a) {
  background-color: red; color: white;
}
.one:-webkit-any(a) {
  background-color: red; color: white;
}

.two:not(div) {
  background-color: orange; color: green;
}
<div class="one">one</div>
<div class="two">two</div>
<a class="one">link</a><br>
<a class="two">link2</a><br>

Upvotes: 2

Josh Crozier
Josh Crozier

Reputation: 240908

No, a simple selector always starts with a type selector or a universal selector. In other words, you can't have a type selector, such as a, follow a class selector.

From the CSS selector specification regarding the syntax of selectors (emphasis added):

4. Selector syntax

A selector is a chain of one or more sequences of simple selectors separated by combinators. One pseudo-element may be appended to the last sequence of simple selectors in a selector.

A sequence of simple selectors is a chain of simple selectors that are not separated by a combinator. It always begins with a type selector or a universal selector. No other type selector or universal selector is allowed in the sequence.

To clarify that last point, the presence of a universal selector is implied in cases such as .class (which means that .class is equivalent to *.class).

6.2. Universal selector

If a universal selector represented by * (i.e. without a namespace prefix) is not the only component of a sequence of simple selectors or is immediately followed by a pseudo-element, then the * may be omitted and the universal selector's presence implied.

Upvotes: 2

Jesse
Jesse

Reputation: 508

No, that syntax does not exist. For what purpose would you like to use it?

Here's a full list of the CSS selector options, through CSS3: https://www.w3schools.com/cssref/css_selectors.asp

Upvotes: 1

Related Questions