简体   繁体   English

如何纵向和横向对齐两个具有不同字体大小的跨距

[英]How to align both vertically and horizontally two spans with different font sizes

I have two spans with text of different font size inside a paragraph. 我有两个跨度,段落内有不同字体大小的文本。 I want to horizontal align them left and right accordingly. 我想相应地左右水平对齐它们。 I also want to vertical align them at baseline. 我还想在基线处垂直对齐它们。 As you can see in this JSFiddle I cannot do both of them at the same time with text-align neither with float. 正如你在JSFiddle中看到的那样,我不能同时使用text-align和float来同时执行这两个操作。

html : HTML:

<p>
<span class="one">Something</span>
<span class="two">Something Else</span>
</p>

css : css:

p {
    border: 1px solid black;
}

p span {
    vertical-align: baseline;
}

.one {
    font-size: 2.0em;
}

.two {
    /* text-align: right; */
    float: right;
    font-size: 3.0em;
}

One way of doing this is to make use of the text-align-last property, which can justify the contents a one-line paragraph to both margins. 这样做的一种方法是使用text-align-last属性,该属性可以将内容作为两行边距的单行段落。 Then make the spans inline-block to prevent the spaces inside the spans from expanding. 然后使跨度inline-block以防止跨距inline-block的空间扩展。

p {
   border:1px solid black;
   text-align:justify;
   -moz-text-align-last:justify;
   text-align-last:justify;
}

p span {
   vertical-align:baseline;
   display:inline-block;
}

And that's it. 就是这样。 No floating, no text-aligning the spans. 没有浮动,没有文本对齐跨度。 See fiddle . 小提琴

An alternative approach is to use flex boxes. 另一种方法是使用柔性盒。
Note that when the paragraph is a flex, vertical-align no longer works, you will need to use align-items . 请注意,当段落是flex时, vertical-align不再起作用,您将需要使用align-items Then add a left margin of auto to the rightmost span to flush it to the right. 然后在最右边的跨度上添加一个auto左边距,将其向右冲洗。

p {
   border:1px solid black;
   display:-webkit-flex;
   display:-moz-flex;
   display:flex;
   -webkit-align-items: baseline;
   align-items: baseline;
}

.one {
   font-size:2.0em;
}

.two {
   font-size:3.0em;
   margin-left:auto;
}

See other fidde . 其他fidde

Which approach you want to use may depend on your audience. 您想要使用哪种方法可能取决于您的受众。 The first one doesn't work in older versions of Chrome, where it has only been defined in v35. 第一个版本不适用于旧版本的Chrome,它只在v35中定义。 The second one doesn't work in IE versions below 11. 第二个在11以下的IE版本中不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM