开发者

HTML: can I place subscript text right under the superscript?

开发者 https://www.devze.com 2022-12-08 13:49 出处:网络
I have a word, which has both superscript a开发者_开发百科nd subscript. Now I render it like this word<sub>1</sub><sup>2</sup>

I have a word, which has both superscript a开发者_开发百科nd subscript. Now I render it like this word<sub>1</sub><sup>2</sup> And get the following:

word12.

How can I put the subscript exactly under the superscript?


Here's a clean solution. Create two CSS classes:

.nobr {
   white-space: nowrap;
}
.supsub {
   display: inline-block;
   margin: -9em 0;
   vertical-align: -0.55em;
   line-height: 1.35em;
   font-size: 70%;
   text-align: left;
}

You might already have the "nobr" class as a <nobr> replacement. Now to express the molecular formula for sulfate, use the "supsub" class as follows:

<span class="nobr">SO<span class="supsub">2-<br />4</span></span>

That is, enclose your superscript/subscript within the "supsub" class, and put a <br /> between them. If you like your superscripts/subscripts a bit larger or smaller, then adjust the font size and then tinker with the vertical-align and line-height. The -9em in the margin setting is to keep the superscripts/subscripts from adding to the height of the line containing them; any big value will do.


There are many ways you can do this with CSS, and each has their pros and cons. One way would be to use relative positioning. A quick example might work like this:

<span class="fraction">
  <span class="numerator">3</span>
  <span class="denominator">4</span>
</span>

And the CSS to go along with this:

span.fraction { }

/* Or child selector (>) if you don't care about IE6 */
span.fraction span.numerator { 
  position:relative;
  top:-0.5em;
}

span.fraction span.denominator {
  position:relative;
  top:0.5em;
  left:-0.5em; /* This will vary with font... */
}

This particular example would work better if you use a monospaced font.


Use the CSS table style (except for IE8 and below). HTML:

<span class="over-under">
  <span class="over">sup</span>
  <span class="under">sub</span>
</span>

CSS:

span.over-under {
  position: relative;
  top: 1em;
  display: inline-block;
}
span.over-under > .over {
  display: table-row;
}
span.over-under > .under {
  display: table-row;
}

Fiddle: https://jsfiddle.net/FredLoney/Loxxv769/4/

Besides being simpler than relative position tweaks, this solution avoids layout distortions that arise from those alternatives. See, e.g., https://jsfiddle.net/FredLoney/da89nyk2/1/.


Well, you can't do that with plain vanilla HTML. Like it's been mentioned, use CSS. But you will want some positioning aswell!

0

精彩评论

暂无评论...
验证码 换一张
取 消