1
<div data-age="30">30</div>

Is there a way to have (PURE CSS) div in red when age<18 and in blue where age>18

yarek
  • 11,278
  • 30
  • 120
  • 219
  • 1
    No. A data attribute is a string not a value – Paulie_D Mar 23 '20 at 18:23
  • You will have to incorporate JQuery or JavaScript. But it is not that difficult. – DumbCoder7 Mar 23 '20 at 19:12
  • 1
    with CSS , you need a few selectors : example to start from: `div[data-age]/* + 1-9 */ {color:red} div[data-age="19"], div[data-age^="2"]/* 20's */ /* etc ... */ {color:initial}` – G-Cyrillus Mar 23 '20 at 19:12
  • here is an example https://codepen.io/gc-nomade/pen/zYGmYZo (click on the arrow at top right where code stands then click on View compiled HTML or CSS to copy the html or css generated ) – G-Cyrillus Mar 23 '20 at 20:34

1 Answers1

2

Here is an idea based on this previous answer where you can consider CSS variables:

.box {
  font-size:30px;
  padding:5px;
  display:inline-block;
  font-family:monospace;
  overflow:hidden;
  color:#fff;
  background:
     linear-gradient(red,red) 0 0/100% calc((18 - var(--a))*1px),
     blue;
}
.box:before {
  content:attr(style);
  text-indent:-4ch;
  display:inline-block;
}
<div style="--a:30" class="box"></div>
<div style="--a:18" class="box"></div>
<div style="--a:9 " class="box"></div>
<div style="--a:17" class="box"></div>
<div style="--a:0 " class="box"></div>

You can also do it for text coloration:

.box {
  font-size:30px;
  padding:5px;
  display:inline-block;
  font-family:monospace;
  overflow:hidden;
  border:5px solid transparent;
  background:
     linear-gradient(#fff,#fff) padding-box,
     linear-gradient(red,red) 0 0/100% calc((18 - var(--a))*1px),
     blue;
}
.box:before {
  content:attr(style);
  text-indent:-4ch;
  display:inline-block;
  color:transparent;
  background:
     linear-gradient(red,red) 0 0/100% calc((18 - var(--a))*1px),
     blue;
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
}
<div style="--a:30" class="box"></div>
<div style="--a:18" class="box"></div>
<div style="--a:9 " class="box"></div>
<div style="--a:17" class="box"></div>
<div style="--a:0 " class="box"></div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415