I want to create plus symbol using CSS. this is the final output need to be shown.
But the challenge is, to create this icon using,
- only use one div tag
- use before/after pseudo-elements
- can't use keyboard '+' icon as a base.
I want to create plus symbol using CSS. this is the final output need to be shown.
But the challenge is, to create this icon using,
#plus {
/* change this value to the desired width */
--width: 40px;
/* setting the background color */
background-color: black;
/* setting height and width with the value of css variable */
width: var(--width);
height: var(--width);
/* perfect circle */
border-radius: var(--width);
/* centrering */
display: grid;
place-items: center;
/* don't delete this, is important for the ::before and ::after pseudoelements */
position: relative;
}
#plus::before,
#plus::after {
content: "";
/* using css calc() https://developer.mozilla.org/en-US/docs/Web/CSS/calc */
/* height and width relative to css variable, change to what you feel is good */
height: calc(var(--width) / 1.5);
width: calc(var(--width) / 5);
/* coloring the pseudoelements */
background-color: white;
/* here the TRICK, using calc() we easily canculate the rotation, without hardcoding this value */
transform: rotate(calc(var(--i) * 90deg));
/* important don't delete */
position: absolute;
}
#plus::before {
--i: 1;
}
#plus::after {
--i: 2;
}
<div id="plus"></div>
this code is relative to the width of the element, so just change the width and all the elements inside will be changed automatically!
#plus {
--width: 5rem; /* change this value if you need */
}
or here directly on your element (if you have multiple same buttons)
<div id="plus" style="--width: 100px;"></div>
for this I am using CSS variables, make sure to see this before https://developer.mozilla.org/en-US/docs/Web/CSS/var
Example:
so now you can see, the div remain always the same as with big values
the code:
#plus {
/* change this value to the desired width */
--width: 5rem;
/* setting the background color */
background-color: black;
/* setting height and width with the value of css variable */
width: var(--width);
height: var(--width);
/* perfect circle */
border-radius: var(--width);
/* centrering */
display: grid;
place-items: center;
/* don't delete this, is important for the ::before and ::after pseudoelements */
position: relative;
}
#plus::before,
#plus::after {
content: "";
/* using css calc() https://developer.mozilla.org/en-US/docs/Web/CSS/calc */
/* height and width relative to css variable, change to what you feel is good */
height: calc(var(--width) / 1.5);
width: calc(var(--width) / 5);
/* coloring the pseudoelements */
background-color: white;
/* here the TRICK, using calc() we easily canculate the rotation, without hardcoding this value */
transform: rotate(calc(var(--i) * 90deg));
/* important don't delete */
position: absolute;
}
#plus::before {
--i: 1;
}
#plus::after {
--i: 2;
}
<div id="plus"></div>