如何垂直对齐伪元素?

时间:2018-08-07 15:25:27

标签: html css css3

我有一个articleSubTitle的伪元素前后。当我有一个小容器或在移动设备上,articleSubTitle中的文本降到新行时,我遇到了一个问题。这是由于after元素恰好落在最后一个单词之后(请参见代码段)。

我想要的是将articleSubTitle作为一个完整的元素,并将之前和之后的元素始终放置在其中,尽管可能要花多长时间。我发布了图片,但是上传者一直上传失败。

我尝试制作articleSubTitle display:blockdisplay:inline-block。这些尝试都没有帮助。

有人知道我该怎么做吗?

.container {
  width: 70%;
  background: gray;
}

.articleSubTitle {
  font-family: 'Nunito', sans-serif;
  font-size: 1.3rem;
  color: #4d4d4d;
}

.articleSubTitle:before,
.articleSubTitle:after {
  content: '';
  display: inline-block;
  vertical-align: middle;
  width: 70px;
  height: 1px;
  background: #2f2f2f;
}

.articleSubTitle:before {
  margin-right: 10px;
}

.articleSubTitle:after {
  margin-left: 10px;
}
<div class="container">
  <h4 class="articleSubTitle center">From the company A & the company B</h4>
</div>

2 个答案:

答案 0 :(得分:3)

使用flexbox:

XCTAssertEqaul(foo.anotherDerivedComputation(), 20)

.articleSubTitle {
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}
.container {
  background: silver;
}

.articleSubTitle {
  font-family: 'Nunito', sans-serif;
  font-size: 1.3rem;
  color: #4d4d4d;
}

.articleSubTitle {
  display: flex;
  justify-content: center;  /* center horizontally */
  align-items: center;      /* center vertically */
  text-align: center;       /* center text inside */
}

.articleSubTitle:before,
.articleSubTitle:after {
  content: '';
  width: 70px;
  height: 1px;
  background: #2f2f2f;
}

.articleSubTitle:before {
  margin-right: 10px;
}

.articleSubTitle:after {
  margin-left: 10px;
}

答案 1 :(得分:1)

一种解决方案是使元素成为flexbox容器:

First Name: {{ user.first_name }}
last Name: {{ user.last_name }}
Email: {{ user.email }}
.container {
  width: 70%;
  background: gray;
}

.articleSubTitle {
  font-family: 'Nunito', sans-serif;
  font-size: 1.3rem;
  color: #4d4d4d;
  display: flex; /*added this*/
  align-items:center; /*added this*/
  justify-content:center; /*added this*/
}

.articleSubTitle:before,
.articleSubTitle:after {
  content: '';
  display: inline-block;
  vertical-align: middle;
  width: 70px;
  height: 1px;
  background: #2f2f2f;
}

.articleSubTitle:before {
  margin-right: 10px;
}

.articleSubTitle:after {
  margin-left: 10px;
}

或使用填充并依靠渐变来创建线条:

<div class="container">
  <h4 class="articleSubTitle center">From the company A & the company B</h4>
</div>
.container {
  width: 70%;
  background: gray;
  text-align:center;
}

.articleSubTitle {
  font-family: 'Nunito', sans-serif;
  font-size: 1.3rem;
  color: #4d4d4d;
  padding:0 80px;
  margin:0;
  display:inline-block;
  background:
   linear-gradient(#2f2f2f,#2f2f2f) left center,
   linear-gradient(#2f2f2f,#2f2f2f) right center;
  background-size:70px 1px;
  background-repeat:no-repeat;
}