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

标签 html css flexbox centering

我试图在元素中心完美对齐的圆圈内显示百分比。太棒了,这行得通。

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

参见代码笔: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>

最佳答案

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

然后用 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

关于html - 不影响居中 HTML 元素的伪元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46248608/

相关文章:

java - 试图在 Java 中获取选项字段的值

image - 具有相同物理像素高度的两个图像具有高度偏移。

css - angular - 单击 flexbox 网格单元以全宽扩展下方区域

html - 将 DIV 宽度限制为父 DIV 宽度(没有显式宽度声明)

javascript - 单击仅在当前 Div 中更改多个 Div 类

javascript - 来自 Google 的简单轮播示例

javascript - 通过 jQuery 打开和关闭 Div

css - 用于更改字体和文本框颜色的 jQuery 验证 CSS 停止工作

html - h2 的 IE8 渲染问题

css - Bootstrap 4 网格 |变量-固定-变量|宽度列,在 IE11 上重叠