首页 > 解决方案 > 如何在未知大小的文本父对象上居中伪元素

问题描述

我正在尝试围绕段落中出现的数字画圈。数字将是一位数或两位数。我希望这些圆圈不会影响我的文本的行高。

我可以对绝对定位进行硬编码,如果数字是一位数,它可以正常工作,但相同的值不适用于两位数。有没有办法定位伪元素,无论它是一位数还是两位数,它都会居中?

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

标签: htmlcss

解决方案


你真的不需要伪垂直对齐+大小就可以了

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

vertical-alignCSS 属性设置内联或表格单元框的垂直对齐方式。

.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;
}
<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>


推荐阅读