Can a CSS Selector Reference Another Selectors Property

Can a CSS selector reference another selectors property?

I added an answer to the question you linked: https://stackoverflow.com/a/11071806/137626

  • You can use the same declaration block with as many selectors as you want by grouping them (selectors are separated by commas)
  • You can't reuse the same declaration block later with a different CSS selector without rewriting the whole declaration block preceded by this selector or using a preprocessor/macro that'll do that for you. Or add it to the existing declaration block as above

Now with your example of an element resized by CSS itself: you could use CSS3 Media Queries and its @media rules containing as many declaration blocks as you want. These media queries would adapt to the width of viewport here.

Mixing expanding elements via animation and media queries that would've the reverse effect will be very soon very complicated (and I'll wonder what content you're playing with); if you want to Keep It Simple, then JS is the way to go. There are variables, loops, events ;) and you can start a CSS3 animation by adding or removing a single class from an element (or whatever CSS selector).

CSS3 won't replace JS (and you shouldn't use JS to style HTML as JS isn't activated or existing everywhere and there's already a nice fallback named CSS).

Is it possible to reference one CSS rule within another?

No, you cannot reference one rule-set from another.

You can, however, reuse selectors on multiple rule-sets within a stylesheet and use multiple selectors on a single rule-set (by separating them with a comma).

.opacity, .someDiv {
filter:alpha(opacity=60);
-moz-opacity:0.6;
-khtml-opacity: 0.6;
opacity: 0.6;
}
.radius, .someDiv {
border-top-left-radius: 15px;
border-top-right-radius: 5px;
-moz-border-radius-topleft: 10px;
-moz-border-radius-topright: 10px;
}

You can also apply multiple classes to a single HTML element (the class attribute takes a space separated list).

<div class="opacity radius">

Either of those approaches should solve your problem.

It would probably help if you used class names that described why an element should be styled instead of how it should be styled. Leave the how in the stylesheet.

Import CSS Selector Styles in Another Selector? (NOT @import)

Not directly, no.

You could do something like this in your HTML:

<div class="original_class overwrite">...</div>

This will have the same effect, but you will have to do this for every element you want styled that way.

There is also the option of using a CSS pre-processor, like SASS, which supports inheritance/mixins.

Specify multiple attribute selectors in CSS

Simple input[name=Sex][value=M] would do pretty nice. And it's actually well-described in the standard doc:

Multiple attribute selectors can be used to refer to several
attributes of an element, or even several times to the same attribute.

Here, the selector matches all SPAN elements whose "hello" attribute
has exactly the value "Cleveland" and whose "goodbye" attribute has
exactly the value "Columbus":

span[hello="Cleveland"][goodbye="Columbus"] { color: blue; }

As a side note, using quotation marks around an attribute value is required only if this value is not a valid identifier.

JSFiddle Demo

Is there a css selector which selects an element outside the current element?

Selectors express structural relationships between elements. When you ask for a selector for an element that is "outside" another element, you're looking for a combinator that says "this element appears outside the containing scope of this other element".

There is no such combinator.

You could conceivably select specifically the .outside sibling of .parent, but then you run into another problem that there is no parent selector for matching .parent relative to .child:hover like there is for matching .child:hover relative to .parent (that is, .parent > .child:hover).

See also: How do I select an element based on the state of another element in the page with CSS?

How do I select an element based on the state of another element in the page with CSS?

The general answer to the canonical question

How do I select an element based on the state of another element in the page with CSS?

is that it depends on exactly three conditions:

  1. whether the state of these elements can be represented using simple selectors,
  2. whether a structural relationship can be expressed between these two elements using combinators to form a single complex selector, and
  3. whether the element that you want to target can be made the subject of the resulting complex selector.

While the current Selectors standard has some interesting and sometimes potentially powerful features, the way it is designed makes it extremely limited in area #2 (with #3 being a direct consequence). Some of these limited possibilities are enumerated in other answers, e.g. through the most basic use of child and sibling combinators, clever use of dynamic pseudo-classes (which actually relates to condition #1), or a combination of both.

The problem given in the question, on the other hand, cannot be solved using what is currently available in Selectors for this reason. Most of this boils down to the lack of either a parent selector and/or a previous sibling selector, both of which may seem like trivial features, but have certain implications that make them difficult to define or implement well. In summary:

  1. Yes, the state of these elements can be represented using simple selectors: div and [data-status~=finished] for the former, and .blink and .spin for the latter two.

  2. The first element can be represented by section > div[data-status~=finished], and the two subject elements can be represented by section + section > .blink and section + section > .spin respectively. The problem is that it's not possible to write a complex selector incorporating all of these structures, because combinators are one-way, and there is no parent counterpart to the child combinator to join them at the first section element.

  3. Assuming the answer to the first two questions is also "yes", each of .blink and .spin can be made the subject of its own complex selector. (But more on that in the next section.)

If you've been directed to this question, chances are the problem you're trying to solve, like the one given above, cannot be solved with Selectors due to these limitations.

The upcoming standard boasts some new features that will greatly enrich selector syntax and potentially open it (and CSS) up to a host of new possibilities, including a possible solution to the example problem. All of these things will be covered in the following sections, but first I'll explain what each condition means and how it relates to the given example:

Element states, and structural relationships between elements

The defining characteristic of a selector is that it represents a certain structure of one or more elements in the document tree. This isn't just something I made up — you can actually find this description in the informative overview of the Selectors standard:

A Selector represents a structure. This structure can be used as a condition (e.g. in a CSS rule) that determines which elements a selector matches in the document tree, or as a flat description of the HTML or XML fragment corresponding to that structure.

Selectors may range from simple element names to rich contextual representations.

Each element is represented by a sequence of one or more simple selectors. This sequence is known as a compound selector (I'm using terminology from Selectors 4 here as it is much clearer than what is used in Selectors 3 — see this answer for a non-exhaustive list of terms).

Each simple selector represents a certain state of an element. There are simple selectors for matching the type (or tag name) of an element, a class name, an ID, or an arbitrary attribute. There are also pseudo-classes, which represent abstractions and other special states not directly represented within the document tree, such as the order and position of an element in its hierarchy (:nth-child(), :nth-of-type()), user interactions (:hover, :active, :focus, :checked), the visitedness of a hyperlink (:link, :visited), and much more.

In the given example, the div element with a data-status attribute whose space-delimited value contains finished can be represented with a type selector and an attribute selector:

div[data-status~=finished]

If you want the selector to apply only when the pointer is over this element, simply throw in a :hover pseudo-class:

div[data-status~=finished]:hover

Compound selectors are linked via combinators to form complex selectors. These combinators, the >, + and ~ symbols that you may be familiar with, express a relationship between the elements represented by each compound selector. With these two tools alone, you're already able to create some very interesting results as shown in the other answers here. I explain these basics in even further depth in this answer.

In the given example, the following structural relationships can be established:

  • The first section element is the parent of div[data-status~=finished]. This is represented using the child combinator >:

    section > div[data-status~=finished]
  • The second section immediately follows the first one as its sibling. This is represented using the adjacent sibling combinator +:

    section + section
  • Additionally, the second section is the parent of both .blink and .spin. This can be represented using two selectors, one for each child:

    section + section > .blink, 
    section + section > .spin

    Why are two selectors required? In this case it's mainly because there is currently no syntax for subgrouping two compound selectors into one, so you will have to represent each child element separately. The upcoming Selectors 4 standard introduces a :matches() pseudo-class that will provide this very subgrouping functionality:

    section + section > :matches(.blink, .spin)

Now, since every compound selector in a complex selector represents one element, and thus section + section represents two elements that are siblings, section > div represents a parent and a child, and section + section > div represents a child of a next-sibling, you would think that a parent combinator and a previous-sibling combinator are quite redundant. So why do we commonly get these questions:

  • Is there a CSS parent selector?
  • Is there a "previous sibling" CSS selector?

And, more importantly, why is the answer to both of these questions no? The reason is addressed in the next point:

Subject of a selector

The subject of a selector is always represented by the rightmost compound selector. For example, the selector section + section > div represents three elements, of which div is the subject. You might say that the div is selected, or targeted, as in the question, but if you've ever wondered if there was a proper term, it's known as the subject of the selector.

In a CSS rule, styles are applied to the element represented by the subject of the selector. Any child boxes and pseudo-element boxes inherit the styles from this element where appropriate. (The exception is if the subject of the selector includes a pseudo-element, in which case the styles are applied directly to the pseudo-element only.)

Taking the selectors from the previous section, we have the following:

  • The subject of section > div[data-status~=finished] is div[data-status~=finished].
  • The subject of section + section is the second section selector.
  • The subjects of section + section > .blink, section + section > .spin are .blink and .spin respectively.
  • Using :matches(), the subject of section + section > :matches(.blink, .spin) is :matches(.blink, .spin).

It might seem therefore that we do need a parent selector or a previous-sibling selector. But remember that selectors can already represent complex structures. Instead of simply adding new combinators that work opposite of existing ones, it makes sense to seek out a more flexible solution, and that is exactly what the CSSWG has been doing.

Which brings us to the following from the original question:

Is there a CSS selector that would let me specify which elements should get selected based on target element state?

The answer to this is no, and will remain no. However, in the earlier drafts of Selectors 4 (from the FPWD up to the latest working draft from May 2013), there was a proposal for a new feature that would let you pick any of the compound selectors other than the rightmost one, and designate that as the subject of the selector.

A potential solution

However, the subject indicator was recently removed in favor of the :has() pseudo-class (that was in turn adopted from jQuery). I speculate on a likely reason here:

The reason :has() is more versatile is because, with the subject selector, it was never made clear in any draft if a single complex selector could have more than one subject selector (since a single complex selector can only ever have one subject) and/or if functional pseudo-classes such as :matches() accepted the subject selector. But because a pseudo-class is a simple selector, you know that :has() can be accepted anywhere a pseudo-class is accepted.

So while you cannot change the subject of a selector, :has() will completely write off the need to do so, due to its pseudo-class nature. And the best part is that it does this — and then some — all without fundamentally changing selector syntax.

In fact, the example problem can be solved using Selectors 4's :has():

/* Combined with the :matches() example from above */
section:has(> div[data-status~=finished]) + section > div:matches(.blink, .spin)

Notice the use of a child combinator: this scopes the relative selector argument to just children of the first section. Yes, this is the elusive "parent selector" that Web developers the world over have been wanting for years.

And since :has() comes from jQuery, you can use it today, although :matches() doesn't exist yet so you'll have to replace that with a call to .filter() in the meantime:

$('section:has(> div[data-status~=finished]) + section > div')    .filter('.blink, .spin')    .css('color', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><section>    <div>Element 1</div>    <div data-status="finished">Element 2</div>    <div>Element 3</div></section><section>    <div>Element 4</div>    <div class="blink">Element 5</div>    <div>Element 4</div>    <div>Element 4</div>    <div class="spin">Element 4</div>    ...</section>

How to reference another style class for complex selectors with material-ui

MUI uses CSS-in-JS

Use $ruleName to reference a local rule name within the same makeStyles style sheet.

const useStyles = makeStyles({
Header: {
fontWeight: "bold",
display: "flex"
},
CloseButton: {
padding: 0,
borderWidth: 0,

"&:before": {
content: "'x'"
},

"$Header > &": { // <-- pay attention to usage of $
marginLeft: "auto"
}
}
});

Below is what your CSS would look like:

Sample Image

CSS Selector (A or B) and C?

is there a better syntax?

No. CSS' or operator (,) does not permit groupings. It's essentially the lowest-precedence logical operator in selectors, so you must use .a.c,.b.c.

Can I write a CSS selector selecting elements NOT having a certain class or attribute?

Typically you add a class selector to the :not() pseudo-class like so:

:not(.printable) {
/* Styles */
}

:not([attribute]) {
/* Styles */
}

But if you need better browser support (IE8 and older don't support :not()), you're probably better off creating style rules for elements that do have the "printable" class. If even that isn't feasible despite what you say about your actual markup, you may have to work your markup around that limitation.

Keep in mind that, depending on the properties you're setting in this rule, some of them may either be inherited by descendants that are .printable, or otherwise affect them one way or another. For example, although display is not inherited, setting display: none on a :not(.printable) will prevent it and all of its descendants from displaying, since it removes the element and its subtree from layout completely. You can often get around this by using visibility: hidden instead which will allow visible descendants to show, but the hidden elements will still affect layout as they originally did. In short, just be careful.

CSS Selector that applies to elements with two classes

Chain both class selectors (without a space in between):

.foo.bar {
/* Styles for element(s) with foo AND bar classes */
}

If you still have to deal with ancient browsers like Internet Explorer 6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar in this case) instead, regardless of what other classes you list.

To illustrate how other browsers and IE6 interpret this, consider this snippet:

* {
color: black;
}

.foo.bar {
color: red;
}
<div class="foo">1. Hello Foo</div>
<div class="foo bar">2. Hello World</div>
<div class="bar">3. Hello Bar</div>


Related Topics



Leave a reply



Submit