如何将假元素居中在大小未知的文本父对象上

时间:2019-07-09 19:48:59

标签: html css

我正在尝试围绕出现在段落中的数字绘制圆圈。数字将是一个或两个数字。我希望圈子不影响我的文字的行高。

我可以对绝对位置进行硬编码,如果数字是一位数字,它可以很好地工作,但是相同的值不能用于两位数字。有没有一种方法可以定位伪元素,以使其居中而不管它是一位还是两位数字?

.container {
  max-width: 600px;
  padding: 32px;
  background-color: #DDDDDD;
}

p {
  font-size: 1.15em;
  font-family: Proxima Nova, sans-serif;
  line-height: 1.5;
}

.number-pick--in-text {
  display: inline-block;
  position: relative;
  z-index: 1;
  margin: 0 10px;
}


.number-pick--in-text::before {
  content: '';
  position: absolute;
  z-index: -1;
  width: 1.5em;
  height: 1.5em;
  top: -1px;
  right: -12px;
  border-radius: 50%;
  border: 1px solid #79818B;
}
<section class="container">
  <p class="article--text">
    Brandon used his own birthday for his lucky lotto numbers. He picked 
    <span class="number-pick--in-text">1</span> 
    <span class="number-pick--in-text">3</span> 
    <span class="number-pick--in-text">9</span> 
    <span class="number-pick--in-text">12</span> 
    <span class="number-pick--in-text">43</span>  
    <span class="number-pick--in-text">4</span>. 
    He bought his ticket at a local convience store and found out the next day that he won the $150 million jackpot.
  </p>
</section>

2 个答案:

答案 0 :(得分:0)

您实际上并不需要伪,垂直对齐+大小

  

https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align

     

man bash CSS属性设置嵌入式或表格单元格的垂直对齐方式。

vertical-align
.container {
  max-width: 600px;
  padding: 32px;
  background-color: #DDDDDD;
}

p {
  font-size: 1.15em;
  font-family: Proxima Nova, sans-serif;
  line-height: 1.5;
}

.number-pick--in-text {
  display: inline-block;
  vertical-align:middle;/* adjust value to your needs */
  text-align:center;  
  width: 1.5em;
  line-height: 1.5em;
  border-radius: 50%;
  border: 1px solid #79818B;
}

答案 1 :(得分:0)

使用标准方法:

<section class="container">
  <p class="article--text">
    Brandon used his own birthday for his lucky lotto numbers. He picked 
    <span class="number-pick--in-text">1</span> 
    <span class="number-pick--in-text">3</span> 
    <span class="number-pick--in-text">9</span> 
    <span class="number-pick--in-text">12</span> 
    <span class="number-pick--in-text">43</span>  
    <span class="number-pick--in-text">4</span>. 
    He bought his ticket at a local convience store and found out the next day that he won the $150 million jackpot.
  </p>
</section>

left: 50%;
top: 50%;
transform: translate(-50%, -50%);
.container {
  max-width: 600px;
  padding: 32px;
  background-color: #DDDDDD;
}

p {
  font-size: 1.15em;
  font-family: Proxima Nova, sans-serif;
  line-height: 1.5;
}

.number-pick--in-text {
  display: inline-block;
  position: relative;
  z-index: 1;
  margin: 0 10px;
}


.number-pick--in-text::before {
  content: '';
  position: absolute;
  z-index: -1;
  width: 1.5em;
  height: 1.5em;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  border-radius: 50%;
  border: 1px solid #79818B;
}