CSS - Setting padding/margins based on text-width?
Is there a measuring unit in CSS (either planned or already in existence) for setting the padding and margins based on the width of the font being used?
I know that em
is supposed to be the height of the upper-case M of the font the browser uses, which is really handy for adding a clean double-spacing. But I sometimes want the side-margins of inline lists to be the width of a normal non-breaking space, or the width of an upper-case A. With some fonts, using em 开发者_StackOverflow社区is vary unreliable.
The W3C specifications for css3 defines a unit that is the width of the font's "0" character:
ch unit
Equal to the used advance measure of the "0" (ZERO, U+0030) glyph found in the font used to render it.
See css3-values.
Funny, but it seems that nobody cares about width of typeface elements. Everything that's measured, is the height:
If this is the case in "classical typography", then there is even less hope in web typography which is a subclass of the former.
EDIT: Actually there is a measurement named En which refers to " width of a lowercase letter "n"." However, I haven't seen this used in web.
I'm afraid no. CSS does not offer a way to reference fonts properties.
But you can always get away by inserting
in the extra first and last list elements.
I came up with something simple that helped me with a padding issue based on font size. I wanted to offset a <td>
based on a string prefix in the row above. Cliff notes version, I add the text that represents the desired offset in a span and make it invisible and unselectable. My solution is here:
.hiddenOffset {
opacity: 0;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
cursor: default;
}
<table>
<tr>
<td>NumElements</td>
</tr>
<tr>
<td><span class="hiddenOffset">Num</span>Offset Text</td>
</tr>
</table>
This gives me the perfect offset and the prefix is hidden and non-selectable. In my actual code I use pure JavaScript to specify the prefix string so it's not hardcoded and I use prefix.repeat(n)
to set nested indentations.
function processRepeatingGroupInstance(indent, group) {
let prefix = 'No';
let html = '';
for (let i = 0; i < group.length; i++) {
let field = group[i];
if (field.hasOwnProperty('msgvaluedesc'))
html += `<tr><td><span class="hiddenOffset">${prefix.repeat(indent)}</span>${field.name}</td><td class="num">${field.number}</td><td class="value tooltip">${field.msgvaluedesc}<span class="tooltiptext">${field.msgvalue}</span></td></tr>`;
else
html += `<tr><td><span class="hiddenOffset">${prefix.repeat(indent)}</span>${field.name}</td><td class="num">${field.number}</td><td class="value">${field.msgvalue}</td></tr>`;
if (field.hasOwnProperty('repeating_group')) {
for (let j = 0; j < field.repeating_group.length; j++)
html += processRepeatingGroupInstance(indent + 1, field.repeating_group[j]);
}
}
return html;
}
精彩评论