How can I align text in the same tag differently?

时间:2017-04-08 22:31:13

标签: html css text center text-align

So I have some text in-between an h2 tag, and I basically want to have the entire h2 tag centered on the page. But I also want to have some text on a second line, that is aligned to the right.

So it would look something like this: enter image description here

3 个答案:

答案 0 :(得分:1)

您可以使用CSS flexbox 来获得简洁明了的解决方案。

main {                          /* 1 */
  display: flex;
  justify-content: center;
}

h2 {
  display: inline-flex;         /* 2 */
  flex-direction: column;
  align-items: center;
  margin: 0;
}

h2>span {
  margin-left: auto;            /* 3 */
}
<main>
  <h2>
    WebsiteName<span>.com</span>
  </h2>
</main>

注意:

  1. 块级容器;给h2空间水平居中。
  2. 使h2成为内联级容器,因此该框仅与内容一样宽。这允许第一行和第二行对齐。
  3. 将第二行与右侧对齐。
  4. 替代方法,使用 绝对定位 ,根据评论中的反馈:

    h2 {
      display: inline-flex;
      flex-direction: column;
      align-items: center;
      margin: 0;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
    }
    
    h2>span {
      margin-left: auto;
    }
    <h2>
      WebsiteName<span>.com</span>
    </h2>

答案 1 :(得分:0)

You can try the tag or the float property with the defined class.

答案 2 :(得分:0)

by adding the following syntax:

.class_name tag_name