简体   繁体   中英

How to target an element with specific css attribute (CSS Only Solution)?

I have an HTML snippet like below:

<div class="status">
    <div class="status-icon green">
      Online
    </div>
</div>

and related css:

.status {
  width: 100px;
}
.status-icon {
  display: none;
}

My question is:

How can I write a css rule when .status{width=150px} then .status-icon{display: block;} ?

Or is there a selector to target specific css rules like attribute selectors?

You cannot write a CSS rule where a property is set depending on whether the value of another property satisfies some condition. This seems to be what you are asking, even though you refer to CSS attributes. (There are no attributes in CSS; there are attribute selectors, but they refer to HTML or XML attributes.)

CSS as currently defined is simply a style sheet language with no programming features (or, let us say, with very limited programming-like features).

If you define status as a percentage (instead of fixed pixels) then you can do this with media queries

like so:

FIDDLE

.status {
    width: 20%;
    height: 100px;
    background: blue;
}
.status-icon {
    display: none;
    color: white;
}
/* 20% of 750px = 150px */
@media (min-width: 750px) {  
    .status-icon
    {
        display: block;
    }
}

So now when the viewport width hits 750px+ the status element will be 150px wide and with the media media query we can set .status-icon to block

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM