html - 修复了由于 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>
解决方案
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>
希望这是你需要的。
推荐阅读
- database-connection - 使用 R 连接到 teradata 服务器
- mysql - 有一个带有连接和联合的 select 语句,但无法正常工作
- javascript - 使用 dom 元素属性 data-timer-id 调用 setInterval(),只运行一次
- javascript - 嗨,我怎样才能将变量(i)的值放在括号中?
- python - 从 pandas 数据框中删除非 ASCI 字符
- python - 如果 TextIOWrapper 对象没有保存到变量中,它会自动关闭吗?
- javascript - 如何控制 HTML5 Web Worker 上的 XMLHttpRequest 对象?
- android - 不能同时使用矢量可绘制对象作为应用程序图标和 imageView 源
- php - csv 导出中的 php 自定义标题/列标题
- c++ - C ++:父级从子级调用本身尚未声明的函数。如何?