【问题标题】:How do I use CSS to center text vertically in a circle如何使用 CSS 将文本垂直居中在一个圆圈中
【发布时间】:2022-07-15 23:51:48
【问题描述】:

我有一个圆圈网格,在每个圆圈中我试图显示垂直居中的文本。无论我尝试什么,到目前为止都没有任何效果。

代码在 codepen 上:https://codepen.io/slurmclassic/pen/bGvBJPJ

我的 HTML 是这样的:

<div class="grid">
  <a class="grid-item"  href = 'linka'><span>Text A</span></a>
  <a class="grid-item"  href = 'linkb'><span>Text B</span></a>
  <div class="grid-item" ><span>Company Logo</span></div>
  <a class="grid-item" href = 'linkc'><span>Text C</span></a>
  <a class="grid-item" href = 'linkd'><span>Text D</span></a>
</div>

我的 CSS 如下所示:

.grid {
  width: 100%;
  max-width: 500px;
  margin: 0 auto;
  background: #CCC;
}
.grid::after {
  content: "";
  display: block;
  clear: both;
}
.grid-item {
  text-decoration: none;
  overflow: hidden;
  width: 48%;
  padding-bottom: 48%;
  background-color: rgba(124, 139, 224, 0.8);
  border-radius: 50%;
  float: left;  
  margin: 1%;
  margin-top: -4%;
  color: black;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.grid-item > span { 
  color: black;
  text-align: center;
  display: table-cell;
  vertical-align: middle;
  align-items: center;
  justify-content: center;  
  text-align: center;  
}

.grid-item:nth-child(1),
.grid-item:nth-child(2) {
  margin-top: 1%;
}

.grid-item:nth-child(3n + 3) {
  margin-left: 25%;
}

.grid-item:nth-child(3n + 4) {
  clear: left;
}

我尝试将文本放在 span 中,以便我可以尝试将问题与“grid-item”类分开来解决,但这没有帮助。

我可以通过应用将文本向下移动的变换来蛮力,但必须有更好的方法来做到这一点。

我试过 text-align: center, align-items: center, justify-content: center, vertical-align: middle。我尝试将 line-height 设置为 font-size ,但这也没有帮助。

我们将不胜感激任何想法,以及任何可演示的解决方案,谢谢。

【问题讨论】:

    标签: html css


    【解决方案1】:

    我相信这里的问题是.grid-item 上的padding-bottom。尝试用aspect-ratio: 1/1;替换它

    如果您需要支持与aspect-ratio 不兼容的东西,您可以尝试使用::afterpadding-bottom: 100% 之类的伪元素来实现宽高比技巧。更多信息:https://css-tricks.com/aspect-ratio-boxes/

    【讨论】:

      猜你喜欢
      • 2015-03-15
      • 1970-01-01
      • 1970-01-01
      • 2016-07-01
      • 2020-04-22
      • 2015-11-30
      • 2014-10-22
      • 2016-09-16
      • 2011-02-25
      相关资源
      最近更新 更多