伪元素中的垂直对齐与绝对位置

时间:2018-03-28 11:49:40

标签: html css

我有一个“按钮”元素,必须水平居中,我做了 margin: 0 auto;
但是在该按钮旁边,我默认为空:after伪元素,它将包含取决于服务器响应的文本。

现在它的工作原理如下:

.button {
  cursor: pointer;
  position: relative;
  background: gray;
  width: 200px;
  height: 36px;
  line-height: 36px;
  margin: 0 auto;
  text-align: center;
}
.button:after {
  cursor: default;
  text-align: left;
  content:'response text here';
  position: absolute;
  top: 0;
  right: -180px;
  height: 36px;
  width: 170px;
}
<div>
  <div class="button">click me!</div>
</div>

并且工作正常,但如果该响应文本包含2行(可能发生),则由于line-height参数,第二行将不会垂直排列。
所以问题是:在这种情况下如何垂直居中响应文本?

如果我使:after元素display:table-cellposition:absolute而无效,则.button的flexbox也会影响按钮文字。 我想到的另一个解决方案是连续2 <dv>,但如果是这样,我不知道如何定位它们。

4 个答案:

答案 0 :(得分:2)

您可以尝试flex,无需指定line-height:

&#13;
&#13;
.button {
  cursor: pointer;
  position: relative;
  background: gray;
  width: 200px;
  height: 36px;
  margin:10px auto;
  text-align: center;
  display:flex;
  align-items:center;
  justify-content:center;
}
.button:after {
  cursor: default;
  text-align: left;
  content:attr(data-text);
  position: absolute;
  top: 0;
  right: -180px;
  bottom:0;
  width: 170px; 
  display:flex;
  align-items:center;
}
&#13;
<div>
  <div class="button" data-text="response text here">click me!</div>
</div>

<div>
  <div class="button" data-text="response text here response text">click me!</div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您可以将绝对定位的伪元素的line-height重置为normal左右,并使用top: 50% + transform: translateY(-50%)将其垂直居中。

我还建议使用left: 100%而不是right: -180px,以便它可以使用动态按钮宽度。

.button {
  position: relative;
  background: gray;
  width: 200px;
  height: 36px;
  margin: 10px auto;
  text-align: center;
  line-height: 36px;
  cursor: pointer;
}

.button:after {
  content: attr(data-text);
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  left: 100%;
  margin-left: 10px;
  width: 170px;
  text-align: left;
  line-height: normal;
  cursor: default;
  background: pink;
}
<div>
  <div class="button" data-text="response text here">click me!</div>
  <div class="button" data-text="response text response text here">click me!</div>
</div>

答案 2 :(得分:0)

使用transform调整伪元素的位置,使其垂直居中。

使用flexbox对齐按钮文本而不是将继承的line-height

&#13;
&#13;
.button {
  cursor: pointer;
  position: relative;
  background: gray;
  width: 200px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 1em
}

.button:after {
  cursor: default;
  content: 'response text goes here and here here';
  position: absolute;
  top: 50%;
  left: 100%;
  transform: translate(0%, -50%);
  width: 100px;
  text-align: center;
  border: 1px solid red;
}
&#13;
<div>
  <div class="button">click me!</div>
</div>
&#13;
&#13;
&#13;

答案 3 :(得分:-2)

您可以添加如下容器div:

-v c:/dockershared_folder:/mnt/shared

并在CSS中:

<div class="center">
  <div class="button">click me!</div>
</div>
相关问题