代码之家  ›  专栏  ›  技术社区  ›  SNYDERHAUS

不影响居中HTML元素的伪元素

  •  2
  • SNYDERHAUS  · 技术社区  · 7 年前

    但是,我希望数值与中心对齐,而“%”浮在旁边,并且不影响放置。

    请参阅代码笔: https://codepen.io/brycesnyder/pen/MEwddv

    div {
      font-family: sans-serif;
      height: 200px;
      width: 200px;
      background: #ae63e4;
      border-radius: 50%;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      font-size: 60px;
      line-height: 1;
      color: white;
      text-align: center;
    }
    
    div.percent:after {
      content: '%';
      font-size: 30px;
      margin-bottom: 15px;
    }
    
    div.a-percent {
      position: relative;
      background: #0ebeff;
    }
    
    div.a-percent:after {
      content: '%';
      position: absolute;
      font-size: 30px;
      margin-top: 5px;
    }
    <div class="percent">0</div>
    <div class="percent">10</div>
    <div class="percent">100</div>
    
    <br>
    <br>
    
    <div class="a-percent">0</div>
    <div class="a-percent">10</div>
    <div class="a-percent">100</div>
    3 回复  |  直到 7 年前
        1
  •  1
  •   Michael Benjamin    7 年前

    为什么不在数字的左侧添加相同的百分比符号?

    然后用隐藏此副本 visibility: hidden

    这在容器中创建了相等的平衡,数字可以完全居中。

    div {
      font-family: sans-serif;
      height: 200px;
      width: 200px;
      background: #ae63e4;
      border-radius: 50%;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      font-size: 60px;
      line-height: 1;
      color: white;
      text-align: center;
    }
    div::after {
      content: '%';
      font-size: 30px;
      margin-bottom: 15px;
    }
    div::before {
      content: '%';
      font-size: 30px;
      margin-bottom: 15px;
      visibility: hidden;
    }
    div.a-percent {
      background: #0ebeff;
    }
    <div class="percent">0</div>
    <div class="percent">10</div>
    <div class="percent">100</div>
    
    <br>
    <br>
    
    <div class="a-percent">0</div>
    <div class="a-percent">10</div>
    <div class="a-percent">100</div>

    更多详细信息和其他选项: Center and right align flexbox elements

        2
  •  0
  •   SNYDERHAUS    7 年前

    div {
      height: 200px; width: 200px;
      background: maroon;
      border-radius: 50%;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
      color: white;
      &.percent {
        &:after {
          content: '%';
          position: absolute;
      }
    }
    
        3
  •  0
  •   Zina Taklit    7 年前

    试试这个:

    div {
        font-family: sans-serif;
        height: 200px; width: 200px;
        background: #ae63e4;
        border-radius: 50%;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        font-size: 60px;
        line-height: 1;
        color: white;
        text-align: center;
        &.percent {
            &:after {
                content: '%';
                font-size: 30px;
            }
        }
    }