本质上,我想知道是否有任何机制可以将字体的字符映射到div的维度,更高的字母创建更高的div,等等
有些单位(如em、ex和ch )应该表示字体大小,但这些是整体字体,而不是相对于当前字符的字体。
这在css/html中可能是不可能的。
我创建了这个代码示例,红色是div界,蓝色是我想要的输出
body {
margin : 5px 0 0 5px;
padding : 0;
display : inline-flex;
flex-flow : column;
}
.set {
display : inline-flex;
flex-flow : row;
padding : 0;
}
.overlay {
position : absolute;
margin : 5px 0px 5px 5px;
width : 60px;
box-shadow : 0 0 0 2px blue;
}
.text {
margin : 5px 5px 5px 5px;
font-family : sans-serif;
font-size : 32px;
line-height : 32px;
box-shadow : 0 0 0 2px red;
width : 60px;
text-align : center;
}
.overlay.overlay-1 {
margin-top : -26px;
height : 13px;
}
.overlay.overlay-2 {
margin-top : -34px;
height : 22px;
}
.overlay.overlay-3 {
margin-top : -28px;
height : 23px;
}<html>
<body>
<div class="set">
<div>
<div class="text">xxx</div>
</div>
<div>
<div class="text">xxx</div>
<div class="overlay overlay-1"></div>
</div>
</div>
<div class="set">
<div>
<div class="text">Xxx</div>
</div>
<div>
<div class="text">Xxx</div>
<div class="overlay overlay-2"></div>
</div>
</div>
<div class="set">
<div>
<div class="text">xxy</div>
</div>
<div>
<div class="text">xxy</div>
<div class="overlay overlay-3"></div>
</div>
</div>
</body>
</html>
发布于 2022-07-26 16:29:36
似乎没有用CSS实现这一目标的编程方法,因为CSS中的相对高度指的是字体大小,而不是单个字符。
编辑:找到一个Javascript代码,它将一行文本转换为图像,然后测量图像大小(以像素为单位)。也许你可以用这个。
function measureTextHeight(fontSizeFace) {
// create a temp canvas
var width = 1000;
var height = 60;
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
// Draw the entire a-z/A-Z alphabet in the canvas
var text = "o";
ctx.save();
ctx.font = fontSizeFace;
ctx.clearRect(0, 0, width, height);
ctx.fillText(text, 0, 40);
ctx.restore();
// Get the pixel data from the canvas
var data = ctx.getImageData(0, 0, width, height).data,
first = false,
last = false,
r = height,
c = 0;
// Find the last line with a non-transparent pixel
while (!last && r) {
r--;
for (c = 0; c < width; c++) {
if (data[r * width * 4 + c * 4 + 3]) {
last = r;
break;
}
}
}
// Find the first line with a non-transparent pixel
while (r) {
r--;
for (c = 0; c < width; c++) {
if (data[r * width * 4 + c * 4 + 3]) {
first = r;
break;
}
}
// If we've got it then return the height
if (first != r) return last - first;
}
// error condition if we get here
return 0;
}
https://stackoverflow.com/questions/73125849
复制相似问题