How to rotate pseudo element css

半腔热情 提交于 2020-01-24 09:53:25

问题


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

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.


回答1:


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;
}



回答2:


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

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>



回答3:


modify the style of #pseudo::after as right: 0;

#div {
  background: blue;
  width: 80px;
  height: 80px;
  transform: rotate(45deg);
}

/* tested but not working */
#pseudo::after,
#pseudo::before {
  /* transform-origin: 50% 50%; */
}


#pseudo::after {
  content: '›';
  font-size: 50px;
  color: green;
  right: 0;
  position: absolute;
  transform: rotate(90deg);
  top: 40px;
}

#pseudo::before {
  content: '›';
  font-size: 50px;
  position: absolute;
  color: green;
  right: 10px;
  top: 10px;
  transform: rotate(-90deg);
}
<div id="div"></div>

<div id="pseudo"></div>


来源:https://stackoverflow.com/questions/38613228/how-to-rotate-pseudo-element-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!