Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rotate pseudo element css

I want to recreate this icon using css pseudo elements (as a toggle indicator):

enter image description here

I have created the nececcary pseudo elements using ::after, ::before and tried to rotate them using transform: rotate(90deg).

How can I tell them to rotate around their own center? I have tried transform-origin: 50% 50%; which does not work. Right now, both pseudo elements got the same right: 10px; but they are not placed above each other, instead they are next to each other.

You can check this JS FIDDLE to illustrate the problem.

like image 822
Marian Rick Avatar asked Sep 20 '25 12:09

Marian Rick


2 Answers

First you can use :before and :after pseudo elements and create shape like this DEMO

enter image description here

After that you can rotate parent element for 45deg and get desired result.

.el {
  margin: 50px;
  position: relative;
  transform: rotate(45deg);
  display: inline-block;
}
.el:before,
.el:after {
  content: '';
  width: 30px;
  height: 30px;
  position: absolute;
}
.el:before {
  border-top: 4px solid black;
  border-left: 4px solid black;
  top: -10px;
  left: -10px;
}
.el:after {
  border-bottom: 4px solid black;
  border-right: 4px solid black;
  top: 10px;
  left: 10px;
}
<div class="el"></div>

Update: You can also add some transition on :hover like this

.el {
  margin: 50px;
  position: relative;
  transform: rotate(45deg);
  display: inline-block;
  cursor: pointer;
}
.el:before,
.el:after {
  content: '';
  width: 30px;
  height: 30px;
  position: absolute;
  transition: all 0.3s ease-in;
}
.el:before {
  border-top: 4px solid black;
  border-left: 4px solid black;
  top: -10px;
  left: -10px;
}
.el:after {
  border-bottom: 4px solid black;
  border-right: 4px solid black;
  top: 10px;
  left: 10px;
}
.el:hover:before {
  top: -15px;
  left: -15px;
}
.el:hover:after {
  top: 15px;
  left: 15px;
}
<div class="el"></div>
like image 148
Nenad Vracar Avatar answered Sep 22 '25 01:09

Nenad Vracar


transform-origin works fine, it's just that

a) 50% 50% (the object's center) is the default, and

b) you have to center the content of the box. That's a bit tricky because the icon you use doesn't require the full line height. Try adding

::before, ::after {
  padding-bottom: .17em;
}
like image 26
wortwart Avatar answered Sep 22 '25 03:09

wortwart