Implementation of CSS child element selecting parent element

Time:2020-11-21

Usually, a CSS selector is selected from top to bottom, and the child element is selected through the parent element. Can the parent element be selected through the child element?


<ul>
    <li>
        <a href="#" class="active">1</a>
    </li>
    <li>
        <a href="#">2</a>
    </li>
</ul>

If I want to choose Li with a.active, how can I implement it? At present, there seems to be no way for us to learn CSS. However, a pseudo CSS class, has () which is going to be introduced today, has this function. Although it is still in the draft stage, we can learn about it in advance.


li:has(> a.active){
    color:red;
}

In addition to representing inclusion,: has can also represent sibling following relationships


div:has(+ p){
    color:red;
}

Indicates that the < div > tag is selected, provided that the div tag must be followed by a < p > tag. It can also be used with: not


article:not(:has(a)){
    color:red;
}

Indicates the < article > tag that does not contain < a >. Note the order of: not and has. Different orders represent different meanings


article:has(:not(a)){
    color:red;
}

Represents a < article > tag that contains a non < a >

In fact, what we mentioned earlier: focus within is also a pseudo class that selects the parent element through child elements, but only if the child element gets the focus, while has is more flexible and powerful.


form:focus-within{
    background-color:black;
}

If it is implemented through: has, it can be written as follows


form:has(:focus){
    background-color:black;
}

This article on the implementation of CSS child element selection of parent element is introduced here. For more related content of CSS child element selection of parent element, please search previous articles of developeppaer or continue to browse the related articles below. I hope you can support developeppaer more in the future!

Recommended Today

Explain module, import and export in JavaScript

Author: Tania rascia Crazy technology house Original text:https://www.taniarascia.com/j… In the era of the Internet, websites are mainly developed with HTML and CSS. If you load JavaScript into a page, it usually provides effects and interactions in the form of small fragments. Generally, all JavaScript code is written in a file and loaded into a filescriptTag. […]