"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Align Inline-Blocks Horizontally on the Same Line?

How to Align Inline-Blocks Horizontally on the Same Line?

Published on 2024-11-07
Browse:860

How to Align Inline-Blocks Horizontally on the Same Line?

Aligning Inline-Blocks Horizontally on the Same Line

Problem

Inline-blocks offer advantages over floating elements, such as baseline alignment and automatic centering when the viewport becomes narrow. However, aligning two inline-blocks horizontally on the same line can pose a challenge.

Challenges of Inline-Block Alignment

  • Floats may interfere with baseline alignment and cause unwanted wrap-around.
  • Relative and absolute positioning can lead to spacing issues, similar to floats.

Solution: Using Text Justification

One effective solution involves utilizing the text-align: justify technique:

CSS Code

.header {
    text-align: justify;
    background: #ccc;
}

.header:after {
    content: '';
    display: inline-block;
    width: 100%;
    height: 0;
    font-size: 0;
    line-height: 0;
}

h1 {
    display: inline-block;
    margin-top: 0.321em;
}

.nav {
    display: inline-block;
    vertical-align: baseline;
}

Explanation

  • Set the parent element's text-align to "justify" to distribute text evenly across its width.
  • Add a pseudo-element header:after to consume the remaining space between the inline-blocks.
  • Set the inline-blocks h1 and .nav to display: inline-block and vertical-align: baseline to maintain their baselines.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3