Home >Web Front-end >CSS Tutorial >How Can I Center a Block Element Using Only `display: inline-block` in CSS?

How Can I Center a Block Element Using Only `display: inline-block` in CSS?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-27 03:24:10675browse

How Can I Center a Block Element Using Only `display: inline-block` in CSS?

Centered Display with Inline Block in CSS

In the given code, the body text is aligned to the center using text-align: center. The .wrap class, which previously employed display: table for alignment, now utilizes display: inline-block. This allows for a more flexible layout compared to using a table-like display.

body {
    background: #bbb;
    text-align: center;
}

.wrap {
    background: #aaa;
    margin: 0 auto;
    display: inline-block;
    overflow: hidden;
}

With these changes, the .wrap element maintains its alignment to the center of the page while allowing the content within it to flow naturally, as if it were part of the inline text. This approach eliminates the need for the additional display: table rule, resulting in a more streamlined and versatile CSS code.

The above is the detailed content of How Can I Center a Block Element Using Only `display: inline-block` in CSS?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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