提问者:小点点

如何在固定位置元素中居中元素[重复]


我想为一个笔记应用程序添加笔记加号。我做了一个固定位置的圆,这样它总是可见的。然后,我想做两条线,形成一个加号,并将这些线居中。这是代码:

null

#note-add {
  position: fixed;
  background: rgb(189, 28, 175);
  width: 75px;
  height: 75px;
  bottom: 0;
  right: 50%;
  border-radius: 50%;
  margin-bottom: 30px;
}

.lines {
  position: relative;
  background: red;
  width: 30px;
  height: 5px;
  margin: 5px 0px;
}

#line2 {
  transform: rotate(90deg);
}
<div id="note-add">
  <div class="lines" id="line1">

  </div>
  <div class="lines" id="line2">

  </div>
</div>

null

请告诉我如何将加号居中到固定位置的圆上。谢谢!


共1个答案

匿名用户

不需要内部元素,您可以为此使用伪元素。对于居中,我使用了一种最常见、最稳健的居中方法:

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

以及定位的父级。

下面是它的样子:

.note-add {
  position: fixed;
  background: rgb(189, 28, 175);
  width: 75px;
  height: 75px;
  bottom: 0;
  right: 50%;
  border-radius: 50%;
  margin-bottom: 30px;
}

.note-add::before,
.note-add::after {
  content: "";
  position: absolute;
  background: red;
  width: 30px;
  height: 5px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.note-add::after {
  transform: translate(-50%, -50%) rotate(90deg);
}
<div class="note-add"></div>