简体   繁体   中英

Using class name in CSS value

I am currently doing some styling and have thought up an interesting way to do something. I want to create a piece of text that stands out among every other bit of text on the page. Below you can see the way I've done this.

 var el = document.querySelectorAll('span[class^=impact]')[0], col = el.className.split('-')[1]; el.style.textShadow = '2px 2px 0 #' + col; 
 html, body { width: 100%; height: 100%; margin: 0; background-image: url('http://i.imgur.com/UxB7TDq.jpg'); } [class^=impact] { position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%); font-family: Impact, sans-serif; font-size: 72pt; font-weight: 800; text-transform: uppercase; } 
 <span class="impact-008080">impact</span> 

As you can see I'm basically getting the first half of the class and applying styles to it and grabbing the second half of the class in JavaScript and applying the shadow then. What I want to do is omit the JavaScript completely and keep it all in CSS.

I do not have a list of colours. Any and all hex colours are supported obviously. I would prefer to keep this format.

CSS attr

Theoretically, this type of thing is what the CSS attr property could be used for when browser support exists. Note that this won't work now, but when browser support does exist, it might look something like this:

HTML

<span class="impact" data-shadow="#008080">Impact</span>

CSS

.impact {
    /* you text and positioning styles here */

    text-shadow: 2px 2px attr(data-shadow);
}

You can read more about the attr property here: https://developer.mozilla.org/en-US/docs/Web/CSS/attr


But for now...

Your best bet is probably to continue to use JavaScript, but instead of appending the hex code to the class name, store the hex value in a data attribute of the element, allowing you to keep the class name consistent for all instances of that element.

HTML

<span class="impact" data-shadow="#fff">Impact</span>

CSS

.impact {
    /* your text and position styles here */
}

JS

var el = document.querySelector(".impact"),
    shadow = el.dataset.shadow;

el.style.textShadow = '2px 2px ' + shadow;

Here's a JSFiddle for reference: http://jsfiddle.net/galengidman/xx6r1n2o/

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