如何使大于容器的文本居中?

5

以下是代码:

#add_cal_in {
    width: 30px;
    height: 30px;
    line-height: 30px;
    font-size: 50px;
    text-align: center;
    background-color: #f38268;
    display: inline-block;
    vertical-align: top;
    cursor: pointer;
    color: #fff;
    margin-left: 5px;
}
<span id="add_cal_in">M</span>

如果您运行此代码,您会发现文本“M”并没有像我想象的那样居中。如果将 font-size 更改为30px或更小,则可以正常工作。这是怎么发生的?如何将“M”居中对齐?
另一件事是,虽然“M”不是水平居中的,但它似乎仍然是垂直居中的。但是,如果我将“M”更改为“+”,则它既不会水平居中也不会垂直居中。顺便说一下,在Chrome 53中它完美地工作,我在升级Chrome之后发现了这一点。
抱歉我的英语不好,希望您能理解我的意思。

“M”实际上并不在容器中。您已经给span一个宽度,而50px的字体大小会超出这个宽度。 - sol
4个回答

3

您可以使用Flexbox,如果设置align-items: centerjustify-content: center,则始终会在中居中文本。

span {
  margin: 20px;
  width: 30px;
  height: 30px;
  font-size: 50px;
  text-align: center;
  background-color: #f38268;
  display: inline-block;
  cursor: pointer;
  color: green;
  display: flex;
  align-items: center;
  justify-content: center;
}
<span>M</span>
<span>+</span>
<span>A</span>

另一种选择是使用伪元素添加字母,并使用 position: absolutetransform: translate 来将其居中。

span {
  margin: 20px;
  width: 30px;
  height: 30px;
  font-size: 50px;
  text-align: center;
  background-color: #f38268;
  display: inline-block;
  cursor: pointer;
  position: relative;
}
span:after {
  position: absolute;
  left: 50%;
  top: 50%;
  content: 'M';
  color: green;
  transform: translate(-50%, -50%);
}
<span></span>


你的两个解决方案都很棒~谢谢。但是你可以看到,"+"号在视觉上并不垂直居中。我的猜测是"+"号本身并没有垂直居中。我想我可以使用伪元素来解决这个问题。 - Arjenloeb
看起来有一个像素出了问题,试试加上 padding-top: 1px https://jsfiddle.net/Lg0wyt9u/1696/ - Nenad Vracar

1
我认为只需将宽度和高度改为100%即可。

#add_cal_in {
    width: 100%;
    height: 100%;
    line-height: 30px;
    font-size: 50px;
    text-align: center;
    background-color: #f38268;
    display: inline-block;
    vertical-align: top;
    cursor: pointer;
    color: #fff;
    margin-left: 5px;
}
<span id="add_cal_in">M</span>


你可能会误解我的意思。我想让文本在30*30的框中居中显示。宽度和高度是固定的。 - Arjenloeb

1
您可以使用脚本将字母水平居中:

var marginLeft = ($('#add_cal_in').width() - $('.letter').width())/2;
$('.letter').css('margin-left', marginLeft+'px');
#add_cal_in {
    width: 30px;
    height: 30px;
    line-height: 30px;
    font-size: 50px;
    text-align: center;
    background-color: #f38268;
    display: inline-block;
    vertical-align: top;
    cursor: pointer;
    color: #fff;
    margin-left: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span id="add_cal_in"><span class="letter">M</span></span>


这是个好主意!但我还在想是否有一种不需要脚本的方法。Flexbox 似乎可以解决这个问题。 - Arjenloeb

0

你是指像这样吗?

#add_cal_in {
    width: 30px;
    height: 30px;
    line-height: 30px;
    font-size: 50px;
    text-align: center;
    background-color: #f38268;
    display: inline;
    vertical-align: top;
    cursor: pointer;
    color: #fff;
    margin-left: 5px;
}
<span id="add_cal_in">M</span>


使用 display: inline; height:30px; 是无效的,因为它是一个内联元素。 - kourouma_coder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接