Search code examples
htmlcsstextcentertext-align

How can I align text in the same tag differently?


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


Solution

  • You can use CSS flexbox for a clean and simple solution.

    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>

    Notes:

    1. Block level container; gives h2 the space to be horizontally centered.
    2. Make h2 an inline-level container, so the box is only as wide as the content. This allows the first and second lines to align right.
    3. Align second line to the right.

    Alternative method, using absolute positioning, based on feedback in the comments:

    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>