图像中的垂直和水平中心文本

时间:2017-11-21 23:21:38

标签: html css twitter-bootstrap

我正在研究一些css并试图将文本置于像这样的图像中

enter image description here

我现在所拥有的大多数当时,但是有一些字母组​​合使它具有偏离中心的外观(如2 I)。现在html / css非常直接(应该注意,这是在一个bootstrap导航栏内)

HTML

<a class="btn btn-link dropdown-toggle" data-toggle="dropdown" href="javascript:void(0)">
  <!-- the image (white background, blue circle) -->
  <img alt="Navbar-circle" src="/images/navbar-circle.png?1511208668" />
  <!-- the text to be centered -->
  <span class="circle-name">GK</span>
  <span class="caret dropdown-caret pull-right"></span>
</a>

CSS

image {
  height: 55px;
  width: 60px;
}

span.circle-name {
  color: #777777;
  font-size: 1.2em;
  margin-left: -48px;
}

有效的字母示例如上所述,组合 GK 有效。对于不起作用的2个字母的例子 II (这是2个我的)

就像它提到的那样,这可以确定并且对于很多字母组合来说它很好。但有些字母组合却没有。任何关于如何让它始终居中的建议,无论有什么字母都会非常感激

2 个答案:

答案 0 :(得分:0)

我建议您使用span并为其提供图片的宽度

,而不是在text-align: center;上使用负边距。

有几种方法可以实现您的目标:

  1. 图像作为CSS中的背景例如。 http://jsbin.com/zuvifanohi/edit?html,css,output
  2. 在您的主播容器上使用flexbox + justify-content: center;并绝对定位您的图片

答案 1 :(得分:0)

如果你想尝试绝对定位,你需要一个位置相对的包装。你可以使用a标签。调整边距使字母居中。 -10px是跨度高度的一半。 -13px是跨度宽度的一半。你可以用插入符号做同样的事情。

a.dropdown-toggle  {
  display:inline-block;
  height: 55px;
  width: 60px;
  position:relative;
  padding:0;
}
img {width:100%;height:auto;}
span.circle-name {
  color: #777777;
  font-size: 1.2em;
  position:absolute;
  top:50%;
  left:50%;
  margin: -10px 0 0 -13px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<a class="btn btn-link dropdown-toggle" data-toggle="dropdown" href="javascript:void(0)">
  <!-- the image (white background, blue circle) -->
  <img alt="Navbar-circle" src="https://upload.wikimedia.org/wikipedia/commons/a/ad/Enneagram_circle.png" />
  <!-- the text to be centered -->
  <span class="circle-name">GK</span>
  <span class="caret dropdown-caret pull-right"></span>
</a>