如何在文本内部绝对元素之前垂直对齐?

时间:2015-08-03 14:21:42

标签: css vertical-alignment

我正在尝试垂直对齐用:before CSS编写的中间文本。我无法弄清楚这一点。

似乎是重复的,但我已经尝试了所有我找到的。也许我想念它,但我认为这个案例尚未涉及:绝对元素+文本之前。

这是我到目前为止所做的:

.element {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  border: 3px solid black;
  border-radius: 5px;
  text-align: center;
  height: inherit;
  background-color: rgba(0, 0, 0, 0.2);
}
.element:before {
  content: "Some text to align vertically";
  vertical-align: middle;
}
<div class="element"></div>

1 个答案:

答案 0 :(得分:4)

显示flex或table将很容易做到:

html,
body,
.element {
  height: 100%;
  width: 100%;
  margin:0;
  border-collapse:collapse;
  box-sizing:border-box;
}
.element {
  position: absolute;
  display: table;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  border: 3px solid black;
  border-radius: 5px;
  text-align: center;
  height: inherit;
  background-color: rgba(0, 0, 0, 0.2);
}
.element:before {
  content: "Some text to align vertically";
  display: table-cell;
  vertical-align: middle;
}
<div class="element"></div>

挠曲

.element {
  position: absolute;
  display: flex;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  border: 3px solid black;
  border-radius: 5px;
  text-align: center;
  height: inherit;
  background-color: rgba(0, 0, 0, 0.2);
  align-items:center;
  justify-content:center;
}
.element:before {
  content: "Some text to align vertically";
  }
<div class="element"></div>

.element {
  position: absolute;
  display: flex;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  border: 3px solid black;
  border-radius: 5px;
  text-align: center;
  height: inherit;
  background-color: rgba(0, 0, 0, 0.2);
}
.element:before {
  content: "Some text to align vertically";
  margin:auto;
  }
<div class="element"></div>