Zephyr4434
Zephyr4434

Reputation: 796

Underline some text and center the subscript

enter image description here

Please see attached image. How would I achieve an underline effect like this using CSS?

Upvotes: 0

Views: 428

Answers (3)

Michael Meehan
Michael Meehan

Reputation: 11

I would use absolute positioning and percents to provide you the flexibility to place this in a class and reuse without tweaking. Here is an example

Structure your HTML like so:

<p>This is a simple statment with some <span class="underline">underlined text<span>3</span></span>and a number under it. But it s a bit longer to mix it up.</p>
<p>This is a simple statment with some <span class="underline">underlined text<span>3</span></span>and a number under it. But it s a bit longer to mix it up. But it s a bit longer to mix it up.But it s a bit longer to mix it up.But it s a bit longer to mix it up.But it s a bit longer to mix it up.But it s a bit longer to mix it up.</p>

Structure your CSS like so:

p {
    font-size:1em;
    line-height:2.2em;
}
.underline {
    position:relative;
    width:auto;
    text-decoration:underline;
}
.number {
    position:absolute;
    width:100%;
    top:.5em;
    left:50%;
    text-decoration:none;
}

Another CSS method would be :

p {
    font-size:1em;
    line-height:2.2em;
}
p span {
    position:relative;
    width:auto;
    text-decoration:underline;
}
p span span {
    position:absolute;
    width:100%;
    top:.5em;
    left:50%;
    text-decoration:none;
}

Upvotes: 0

Joeytje50
Joeytje50

Reputation: 19112

I believe this is exactly what you are looking for:

HTML:

<span class="underlined">example text<hr/>#</span>

CSS:

.underlined {
    display:inline-block;
    vertical-align:text-top;
    text-align:center;
}
.underlined hr {
    border:none;
    border-top:1px solid black;
    margin:0;
}

Demo.

The span is displayed as inline-block element, so it'll allow line-breaking elements such as <hr> inside the span. Using that, you can simply put a <hr> between the text itself and the subscript, and you'll have the desired result. The vertical-align is required to make the text itself fit in the regular flow of the text, pushing the subscript to below the text.

Be warned though, this will disrupt the flow of the text. I don't know what you wanted to use this for, but I think there is probably another way to get the result you want, without having to use this.

Upvotes: 4

Mark
Mark

Reputation: 4873

This would take some fine tuning, but something like this might work:

<p>Your <span class="toUnderline">test <span class="subscript">3</span> some</span> more text.</p>|
<style>
   .subscript {
    line-height:-15px;
    letter-spacing:-5px;
    text-decoration:none;    
    }
     .toUnderline{
    text-decoration:underline;
   }
</style>

Upvotes: 0

Related Questions