28
loading...
This website collects cookies to deliver better user experience
<input>
elements for the user interaction and one extra element.<input>
to get more stars. No need to change any CSS code.ltr
and rtl
directiondiv
that contain our inputs and an extra <i>
element. Nothing more!.stars {
--s:50px;
position:relative;
display:inline-flex;
}
.stars input {
width:var(--s);
height:var(--s);
margin:0;
opacity:0;
cursor:pointer;
}
--s
will define the size of our inputs that we make invisible using opacity:0
. Everything is within a flexbox container (an inline
one to easily integrate the star rating like an image or a simple text).i
.stars i {
position:absolute;
inset:0 0 calc(var(--s)*0.1);
pointer-events:none;
/* the star */
--v1:transparent,#000 0.5deg 108deg,#0000 109deg;
--v2:transparent,#000 0.5deg 36deg,#0000 37deg;
-webkit-mask:
conic-gradient(from 54deg at calc(var(--s)*0.68) calc(var(--s)*0.57),var(--v1)),
conic-gradient(from 90deg at calc(var(--s)*0.02) calc(var(--s)*0.35),var(--v2)),
conic-gradient(from 126deg at calc(var(--s)*0.5) calc(var(--s)*0.7) ,var(--v1)),
conic-gradient(from 162deg at calc(var(--s)*0.5) 0 ,var(--v2));
-webkit-mask-size: var(--s) var(--s);
-webkit-mask-composite: xor,destination-over;
mask-composite: exclude,add;
/**/
background:
linear-gradient(rgba(255,0,0,var(--o,0.3)) 0 0),
linear-gradient(gold 0 0)
#ccc;
background-size:
calc(var(--l,0)*var(--s)) 100%,
calc(var(--p,0)*var(--s)) 100%;
background-repeat:no-repeat;
}
pointer-events:none;
to be able to interact with the inputs but still have the mouse cursor on the <i>
.#ccc
) to indicate the number of stars and the non-selected ones--p
):hover
effect (controlled with the variable --l
). I will be using a semi transparent color so we can still see the selected stars.mask
in detail. Not suitable to do it here..stars:focus-within {
outline:1px solid;
}
input:active ~ i{--o:1}
input:nth-of-type(N):checked ~ i {--p:N}
input:nth-of-type(N):hover ~ i {--l:N}
:focus-within
will allow me to style the whole div
when interacting with the inputs (good for accessibility):checked
I update the variable --p
based on the input index. We can easily generate the code using SASS/LESS or by doing some copy/past (it only take few seconds to write the code that can cover up to 20 inputs):hover
we do the same logic but with the variable --l
.background-position
based on the direction attribute and we simply add:[dir="rtl"] .stars i {
background-position: right;
}
margin-inline-end
grid-area:1/1
) with the adequate color. Their width will be controlled with the same variables used to control the gradient. Finally by using margin-inline-end:auto;
they will get placed either at the left
or the right
based on the direction.