In my app I have a button to expand and collapse a list. The "plus" sign means to expand the list and the "minus" to collapse it. But I seem to be unable to center the plus and minus symbols exactly in the middle of the button. Vertically they both appear in the lower part of it.
That’s what I have so far:
And that’s what I want:
Here is my code in CSS:
.accordion-button {
background-color: transparent;
border: none;
cursor: pointer;
color: white;
width: 32px;
height: 32px;
font-size: 14px;
font-weight: bold;
text-align: right;
}
.plus::before {
content: '02B';
font-weight: bold;
font-size: 24px;
}
.minus::before {
content: '2212';
font-weight: bold;
font-size: 24px;
}
The relevant HTML/ТypeScript part of the code:
const [isExpanded, setIsExpanded] = useState<boolean>(false);
const handleAccordionClick = () => {
setIsExpanded(!isExpanded);
};
return (
<button
className={`accordion-button ${isExpanded ? 'minus' : 'plus'}`}
onClick={handleAccordionClick}></button>
);
How can I perfectly center my "plus" and "minus" symbols? Any help is appreciated.
2
Answers
There are several ways to achieve this. In my snippet i’ve used
line-height
andvertical-align
. I also changed the background color of the button for visual purposes.EDIT: Thanks to @Parking Master for pointing out that the button text is not centered in Safari. To fix this
padding: 0
must be added to the.accordion-button
class.One way to center content is using
display: grid;
andplace-items: center;
on the container element containing text.Also you could use react to control text content instead of having it be part of a pseudo element in css like so