Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Comparison Operators

I need to target divs that takes up more than 80% of their parent div, for a progress bar. Considering that we can target a specific width with CSS:

[data-width=80]

How might we target a comparison? This did not work in Firefox or Chrome:

[data-width>=80]

A google search for css comparison operators surprisingly did not turn up anything useful or relevant.

Note that I am targeting a data-* property, which I set together when setting the width in Javascript. Obviously I could just have the Javascript write an over80 class and target that, but there are additional concerns for which I need the targeting done in CSS. For one reason, it is the designer's job to decide at which width the change occurs. For another reason, we are targeting multiple devices, not just desktop web browsers.

Here is the target HTML and the CSS:

<div id='progress-bar-outer'>
    <div id='progress-bar-inner'><span id='percent-indicator'>60%</span></div>
</div>

#progress-bar-outer {
    overflow-y: auto;
    height: auto;
    border: #2072a7 solid 3px;
    position: relative;
}

#progress-bar-inner {
    float: left;
    height: 25px;
    background-color: #2072a7;
    width: 60%;
}

#progress-bar-inner[data-width<80] {
    position: relative;
}

#percent-indicator {
    position: absolute;
    top: 5px;
    right: 10px;
}
like image 456
dotancohen Avatar asked Jan 11 '23 08:01

dotancohen


1 Answers

This is a frequently-asked question, but the answer remains the same: CSS does not provide attribute selectors with numeric operations.

None of the existing attribute selectors work with any sort of value semantic; they only look at values as raw strings, and so only rudimentary string-matching attribute selectors exist at most. The next Selectors specification, Selectors 4, does not appear to introduce any numeric value attribute selectors either, but since it's still in its early stages of development, you could propose this feature if you're able to provide some good use case examples.

On a somewhat related note, the given example [data-width=80] is invalid precisely because tokens starting with a digit are interpreted in CSS as either numeric values or dimensions, and CSS attribute selectors only accept either a string or an identifier in the value component, not a number or dimension. If such a feature makes it to Selectors 4, this restriction may be lifted.

And if we're going to talk about separation of concerns, one could argue that setting a data attribute for a presentational value such as width, especially for the sake of RWD, is questionable in itself. The most sensible solution to this problem would be element queries, which don't exist as yet (as far as I've heard, it's primarily because they're difficult to implement correctly).

At this point, your best bet is in JavaScript, really.

like image 160
BoltClock Avatar answered Jan 19 '23 13:01

BoltClock