首页 > 解决方案 > 修复了由于 Font-Size 而下推 Text 的 Width 和 Height Div

问题描述

我正在做一个操作 HTML 的小项目。我正在尝试将文本放置在div具有固定高度和固定宽度的 a 的中心。一切都已定位absolute。但是,设置字体大小会将文本从实际矩形向下推。在同一页面上,我有另一个矩形(未在下面的示例中显示)它可以正常工作(因为可能是较小的字体?)有人可以向我解释发生了什么,以及如何解决我的问题?

.wrapper {
  position: fixed;
  width: 120px;
  height: 72px;
  border-color: #000000;
  border-style: dotted;
}

#LetterBox.position {
  position: absolute;
  top: -4.719643044619423px;
  left: 13.15069816272966px;
}

#LetterBox.shape {
  width: 99.41917060367455px;
  height: 64.46308661417323px;
  background: red;
}

#LetterBox .font {
  font-size: 41px; /*culprit*/
  font-family: "lucida grande", Times, serif;
  color: #222222;
  text-align: center;
}
<div class="wrapper" id="layout">
  <div id="LetterBox" class="position shape">
    <p class="font">a</p>
  </div>
</div>

标签: htmlcss

解决方案


display:table在父 div 和display:table-cell文本元素上居中文本使用属性。

这是工作代码(我没有将红色背景 div 居中,因为这不是问题):

.wrapper {
  position: fixed;
  width: 120px;
  height: 72px;
  border-color: #000000;
  border-style: dotted;
}

#LetterBox.position {
  position: absolute;
  top: -4.719643044619423px;
  left: 13.15069816272966px;
}

#LetterBox.shape {
  width: 99.41917060367455px;
  height: 64.46308661417323px;
  background: red;
  display: table;
}

#LetterBox .font {
  font-size: 41px; /*culprit*/
  font-family: "lucida grande", Times, serif;
  color: #222222;
  text-align: center;
  display: table-cell; 
  vertical-align: middle;
}
<div class="wrapper" id="layout">
  <div id="LetterBox" class="position shape">
    <p class="font">a</p>
  </div>
</div>

另一个小字体的例子:

.wrapper {
  position: fixed;
  width: 120px;
  height: 72px;
  border-color: #000000;
  border-style: dotted;
}

#LetterBox.position {
  position: absolute;
  top: -4.719643044619423px;
  left: 13.15069816272966px;
}

#LetterBox.shape {
  width: 99.41917060367455px;
  height: 64.46308661417323px;
  background: red;
  display: table;
}

#LetterBox .font {
  font-size: 30px; /*culprit*/
  font-family: "lucida grande", Times, serif;
  color: #222222;
  text-align: center;
  display: table-cell; 
  vertical-align: middle;
}
<div class="wrapper" id="layout">
  <div id="LetterBox" class="position shape">
    <p class="font">a</p>
  </div>
</div>

希望这是你需要的。


推荐阅读