问题
I have a component that I use for a star rating, I decided to use FA icons to do the job by using half stars. Every works great, besides the CSS. I've successfully flipped some of the stars (FA icons only go to one side) so the stars align correctly, they just don't touch. I just need some advice on the easiest way to handle it.
Rater.js
import React, { useState } from 'react'
import {FaStarHalf} from "react-icons/all";
import './Rater.css'
const Rater = () => {
const [rating, setRating] = useState(null);
const [hover, setHover] = useState(null);
const [value] = useState(100);
const [iconValue, setIconValue] = useState(5);
return (
<div>
<select
onChange={e => {
setIconValue(Number(e.target.value));
}}
>
{Array.from(new Array(value), (value, index) => index + 1).map(
value => (
<option key={value} value={value}>
{value}
</option>
)
)}
</select>
<h1> Select Amount of Icons </h1>
{[...Array(iconValue), ...Array(iconValue)].map((icon, i) => {
const value = i + 1;
return (
<label>
<input
type="radio"
name="rating"
value={value}
onClick={() => setRating(value)}
/>
<FaStarHalf
className={i % 2 ? "star-left" : "star"}
color={value <= (hover || rating) ? "#ffc107" : "#e4e5e9"}
size={100}
onMouseEnter={() => setHover(value)}
onMouseLeave={() => setHover(null)}
/>
</label>
);
})}
</div>
);
};
export default Rater
Rater.css
input[type='radio'] {
display: none;
}
.star {
cursor: pointer;
transition: color 200ms;
/*transform: rotate(180deg);*/
}
.star-left {
cursor: pointer;
transition: color 200ms;
transform: scaleX(-1);
}
回答1:
The easiest way to align stuff, is to use flexbox.
You can simply wrap your stars in a container:
<div class="container">
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
<div class="star"></div>
</div>
And then add a bit flexbox magic:
.container {
display: flex;
justify-content: space-between;
align-items: center;
You can easily adjust the margin or padding of the stars. Furthermore you can play with the justify-content
.
回答2:
Create a container that is half the width of the star icon and hide the overflow. Then translate by half the width (x-axis) the left (really the right half) star.
CSS
input[type='radio'] {
display: none;
}
.star-container {
cursor: pointer;
display: inline-block;
height: 2rem;
width: 1rem;
overflow: hidden;
}
.star {
transition: color 200ms;
height: 2rem;
width: 2rem;
}
.star-left {
transform: scaleX(-1) translateX(50%);
}
Star Container
<div className="star-container">
<FaStarHalf
className={i % 2 ? "star star-left" : "star"}
color={value <= (hover || rating) ? "#ffc107" : "#e4e5e9"}
onMouseEnter={() => setHover(value)}
onMouseLeave={() => setHover(null)}
/>
</div>
来源:https://stackoverflow.com/questions/62200257/getting-the-stars-to-line-up-css