Home > Web Front-end > CSS Tutorial > How to Align Inline-Blocks Horizontally on the Same Line?

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

Mary-Kate Olsen
Release: 2024-10-30 22:26:03
Original
483 people have browsed it

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;
}
Copy after login

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.

The above is the detailed content of How to Align Inline-Blocks Horizontally on the Same Line?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template