Danio
Danio

Reputation: 1114

Inline div broken when in p element

I want to have an inline div within text, so that the div contains two lines of text aligned vertically.

The initial solution:

div.chinese-word {
    display: inline-block;
}

div.chinese-word div {
    text-align: center;
}
This is a Chinese word <div class="chinese-word"><div>wǒ</div><div>我</div></div> in an inline div

However, it gets broken whenever I put it inside p paragraph. (it might not be the only case).

Invalid!

div.chinese-word {
    display: inline-block;
}

div.chinese-word div {
    text-align: center;
}
<p>This is a Chinese word <div class="chinese-word"><div>wǒ</div><div>我</div></div> in an inline div</p>

It does not even pass validation. I found out that p must contain inline elements only so I switched to spans. But no matter what styling I use, I can't get the same result.

span.chinese-word {
    display: inline-block;
}

span.chinese-word span {
    text-align: center;
}
<p>This is a Chinese word <span class="chinese-word"><span>wǒ</span><br/><span>我</span></span> in an inline span</p>

Clearly, the texts in spans are not horizontally centered anymore. (Both lines appear to be left-aligned).

The p element might have its own styling so I don't want to manipulate it and rather need context-independent solution.

Upvotes: 1

Views: 104

Answers (2)

Chris Pickford
Chris Pickford

Reputation: 8991

Given your initial fiddle, replace the <div>s with <span>s and update your CSS to the following:

span.chinese-word {
    display: inline-block;
    position: relative;
    top: 0.5em;
}

span.chinese-word span {
    display: block;
    text-align: center;
}

Gives the effect I believe you are after.

https://jsfiddle.net/chrispickford/8n3hcvkL/3/

Upvotes: 2

Hatchet
Hatchet

Reputation: 5428

You're on the right track with setting display: inline-block; on the span.chinese-word. If you remove the line break (<br>), and add display: block; to span.chinese-word span, then the text is centered again:

/* Your example */
span.chinese-word-previous {
    display: inline-block;
}

span.chinese-word-previous span {
    text-align: center;
}

/* Fixed */
span.chinese-word {
    display: inline-block;
}

span.chinese-word span {
    display: block;
    text-align: center;
}
Your example:
<p>This is a Chinese word <span class="chinese-word-previous"><span>wǒ</span><br><span>我</span></span> in an inline div</p>
<br>
<br>
Fixed:
<p>This is a Chinese word <span class="chinese-word"><span>wǒ</span><span>我</span></span> in an inline div</p>

Upvotes: 2

Related Questions