如何在固定位置元素中居中元素

时间:2021-03-19 14:31:27

标签: html css

我想为笔记应用添加笔记做一个加号。我做了一个位置固定的圆圈,以便它始终可见。然后我想制作两条带加号的线,并将这些线居中。这是代码:

#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>

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

1 个答案:

答案 0 :(得分: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>