如何将文本居中于容器中心?

时间:2017-03-14 10:02:15

标签: html css

以下是代码:



EXEC sp_SCOPRO_HLP 
  @dDateFrom = '2017-01-01'
, @dDateTo = '2017-01-31'   

EXEC sp_SCOPRO_HLP 
  @dDateFrom = cast('2017-01-01' as date)
, @dDateTo = cast('2017-01-31' as date)




如果您运行此代码,您可以看到文本" M"没有像我想象的那样集中。如果将#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; }更改为30px或更小,它可以正常工作。那是怎么发生的?我怎样才能使" M"在中间?

另一件事是虽然" M"不是HORIZONTALLY居中,似乎" M"仍然是垂直居中的。但是,如果我改变了" M"对于" +",它不会既不是水平也不是垂直居中。顺便说一句,它在Chrome 53中完美运行,我发现升级Chrome后。

抱歉英语不好,希望你能理解我的意思。

4 个答案:

答案 0 :(得分: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>

答案 1 :(得分:1)

您可以通过脚本水平居中字母:

&#13;
&#13;
var marginLeft = ($('#add_cal_in').width() - $('.letter').width())/2;
$('.letter').css('margin-left', marginLeft+'px');
&#13;
#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;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

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

&#13;
&#13;
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;
}
&#13;
<span>M</span>
<span>+</span>
<span>A</span>
&#13;
&#13;
&#13;

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

&#13;
&#13;
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%);
}
&#13;
<span></span>
&#13;
&#13;
&#13;

答案 3 :(得分: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>