Baumr
Baumr

Reputation: 6294

How to align text differently inside a single inline element with CSS?

This should be interesting. Here's what I'm trying to do with CSS:

  1. The words "An Example Alignment" should be in a single <h1> element.
  2. The word "Alignment" should be on the second line (easy with a <br /> tag).
  3. The word "An" should be smaller than the other words (easy with a <span> tag).

enter image description here

So we have:

<h1><span>An</span> Example <br />Alignment</h1>

But here's the catch:

Here's what it should look like: http://jsfiddle.net/Baumr/H2Pzr/

But that's an ugly solution as there are two <h1> elements.

Any ideas of how to do this with CSS by keeping the HTML the same? Very curious to hear. Thank you in advance.

P.S. I could also put "An" into a separate <span>, but I would prefer to keep everything in a single <h1>.)

Upvotes: 2

Views: 1702

Answers (4)

redShadow
redShadow

Reputation: 6787

I'd do the padding by using two display:inline-block spans, to make sure the right margin is always exactly the same (font width varies, depending on the in-use font face).

<h1>
    <span class="padding">An</span> Example <br>
    <span class="padding"></span> Alignment
</h1>

CSS:

h1 {
    font-size: 30px;
}

.padding {
    font-size: 20px;
    width: 30px;
    display:inline-block;
}

Just beware that IE doesn't always use inline-block the right way (although in this case it should).

Update

An even better solution: http://jsfiddle.net/H2Pzr/9/

Use the table-cell display of elements to automatically put them in two columns:

HTML:

<h1>
<span class="first">An</span>
<div class="second">
    Example <br>
    Alignment
</div>
</h1>

CSS:

h1 {
    font-size: 30px;
}

.first {
    display:table-cell;
    font-size: 20px;
    color: #444;
}
.second {
    display:table-cell;
}

Upvotes: 2

Danield
Danield

Reputation: 125651

Try this: (minimal elements!)

<h1>Example <br>Alignment</h1>​

h1 {
    font-size: 30px;
    margin-left: 31px;
}

h1:before
{
    content: 'An  ';
    font-size: 20px;
    margin-left: -31px;
}

Upvotes: 1

Andy
Andy

Reputation: 1141

I would use two span classes in the same H1 tag:

<h1>
    <span class="small-text">An</span> Example 
    <span class="line-two">Alignment</span>
</h1>

Then update your CSS accordingly:

h1 {
    font-size: 30px;
}

span.small-text {
    font-size: 20px;
}

.line-two{
    display:block;
    margin-left: 31px;
}

You don't even need the <br /> since you can just display the second span as display:block; Updated fiddle here: http://jsfiddle.net/H2Pzr/6/

Upvotes: 1

Anoop
Anoop

Reputation: 23208

use two span with different class see jsfiddle

<h1><span class="first">An</span> Example <br>
    <span class="second">Alignment</span>
    </h1>

Upvotes: 1

Related Questions