垂直对齐伪列表项之前

时间:2017-10-14 00:16:04

标签: html css css-position

所以我在伪线之前做了一个自定义,我试图弄清楚如何将它垂直对齐到我的列表项的中心。怎么做到这一点?我尝试了绝对定位,但是它堆叠了所有这些并将它们放在中间而不是它们在每个列表项上。

.menu {
  background: #ececec;
  width: 200px;
  margin-top: 40px;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 20px;
  transition: 0.5s all ease-in-out;
}

.menu li {
  padding: 10px 0;
  cursor: pointer;
}

.menu ul {
  position: relative;
}

.menu li:before {
  content: '';
  height: 30px;
  width: 3px;
  background-color: #FE715D;
  left: -10px;
  position: absolute;
  border-radius: 20px;
  opacity: 0;
  transition: 0.5s all ease-in-out;
}

.menu li:hover:before {
  transition: 0.5s all ease-in-out;
  opacity: 1;
}
<div class="menu">
  <ul>
    <li class="lifirst">About Me</li>
    <li class="limenu">My Skills<li class="limenu">Portfolio</li>
    <li class="limenu">Contact</li>
  </ul>
</div>

1 个答案:

答案 0 :(得分:1)

为防止堆叠伪元素,您必须为其对应的父元素设置位置。

  

<强>绝对
  该元素从正常文档流中删除;没有为页面布局中的元素创建空间。相反,它相对于其最近的定位祖先(如果有的话)

- position on MDN

换句话说:如果您向position: relative;元素添加<li>,则每个伪元素位置都取决于其对应的列表项:

.menu {
  background: #ececec;
  width: 200px;
  margin-top: 40px;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 20px;
  transition: 0.5s all ease-in-out;
}

.menu li {
  padding: 10px 0;
  cursor: pointer;
  position: relative;
}

.menu ul {
  position: relative;
}

.menu li:before {
  content: '';
  height: 30px;
  width: 3px;
  background-color: #FE715D;
  left: -40px;
  top: 7px;
  position: absolute;
  border-radius: 20px;
  opacity: 0;
  transition: 0.5s all ease-in-out;
}

.menu li:hover:before {
  transition: 0.5s all ease-in-out;
  opacity: 1;
}
<div class="menu">
  <ul>
    <li class="lifirst">About Me</li>
    <li class="limenu">My Skills</l<li class="limenu">Portfolio</li>
    <li class="limenu">Contact</li>
  </ul>
</div>