search
HomeWeb Front-endCSS TutorialIntroduction to 6 ways to achieve perfect vertical and horizontal centering using CSS

Foreword

Due to the positioning problem of HTML language, achieving centering in web pages is not as simple as in Word. Especially when the content style is changing and the width and height of the content are variable, achieving reasonable centering also tests the experience of engineers. There are many articles about centering on the Internet, but they are not complete, so Xiaoqie will summarize various solutions to achieve centering using pure CSS today. If there is anything inappropriate in the article, please point it out!

6 options

1. Absolute positioning+margin: auto

<style type="text/css">
    .wrp {
        background-color: #b9b9b9;
        width: 240px;
        height: 160px;
    }
    .box {
        color: white;
        background-color: #3e8e41;
        width: 200px;
        height: 120px;
        overflow: auto;
    }
    .wrp1 { position: relative; }
    .box1 {
        margin: auto;
        position: absolute;
        left: 0; right: 0; top: 0; bottom: 0;
    }
</style>
<div class="wrp wrp1">
    <div class="box box1">
        <h3 id="完全居中层">完全居中层1:</h3>
        <h3 id="开发工具-nbsp-nbsp-WeX-nbsp-nbsp-高性能轻架构-开源免费-跨端-可视化">开发工具 【 WeX5 】: 高性能轻架构、开源免费、跨端、可视化</h3>
    </div>
</div>

Effect:

Introduction to 6 ways to achieve perfect vertical and horizontal centering using CSS

Implementation principle: Use css positioning rules, set the left and right, up and down positioning to 0, margin to auto, let css calculate the margin value based on positioning, and use a hack to achieve centering. The ruler of the center block (green)

The size needs to be controllable, because CSS also needs to refer to the size value when calculating margin. Since the four sides are 0, the automatically calculated size is the same as the parent container. Whether it is setting width, height or max-

height, max-width, all prevent the size from expanding to the same size as the parent.

2. Absolute positioning + margin reverse offset

<style type="text/css">

.wrp2 { position: relative; }
.box2 {
    position: absolute;
    top: 50%; left: 50%;
    margin-left: -100px; /* (width + padding)/2 */
    margin-top: -75px; /* (height + padding)/2 */
}
</style>
<div class="wrp wrp2">

<div class="box box2">
    <h3 id="完全居中方案二">完全居中方案二:</h3>
    <h3 id="开发工具-nbsp-nbsp-WeX-nbsp-nbsp-高性能轻架构-开源免费-跨端-可视化">开发工具 【 WeX5 】: 高性能轻架构、开源免费、跨端、可视化</h3>
</div>
</div>

Effect:

Introduction to 6 ways to achieve perfect vertical and horizontal centering using CSS

Implementation principle: Since top and left are offset by 50% of the height and width of the parent object , you need to use margin to reversely offset 50% of the width and height of the centered block. Percentage cannot be used in margin, because percentage is for

It belongs to the parent object, so you need to manually calculate the fixed value and specify the margin value. This solution requires a fixed size value to calculate the margin reverse bias value, so solution 2 is slightly worse than solution 1!

3. Absolute positioning + transform reverse offset

<style type="text/css">

.wrp3 { position: relative; }
.box3 {
    margin: auto;
    position: absolute;
    top: 50%; left: 50%;
    -webkit-transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}
</style>
<div class="wrp wrp3">

<div class="box box3">
    <h3 id="完全居中方案三">完全居中方案三:</h3>
    <h3 id="开发工具-nbsp-nbsp-WeX-nbsp-nbsp-高性能轻架构-开源免费-跨端-可视化">开发工具 【 WeX5 】: 高性能轻架构、开源免费、跨端、可视化</h3>
</div>

Effect:

Introduction to 6 ways to achieve perfect vertical and horizontal centering using CSS

Implementation principle: Scheme 3 has the same principle as Scheme 2! The difference is that transform is used instead of margin for reverse offset. Since the calculation basis of transform is the element itself, 50% can be used for reverse offset here. This solution also requires a fixed size value, based on which the browser calculates positioning!

4. display:tabel

<style type="text/css">

.wrp4 { display: table; }
.subwrp4 {
    display: table-cell;
    vertical-align: middle;
}
.box4 {
    margin: auto;
    overflow-wrap: break-word;
    height: auto;
    max-height: 80%;
    max-width: 80%;
}
</style>
<div class="wrp wrp4">

<div class="subwrp4">
    <div class="box box4">
        <h3 id="完全居中方案四">完全居中方案四:</h3>
    </div>
</div>
</div>

Effect:

Introduction to 6 ways to achieve perfect vertical and horizontal centering using CSS

Implementation principle: Option 4 has a better implementation effect. The size of the center block can be used for wrapping. The disadvantage is that a table-cell layer is added to achieve vertical centering. The centered block of option 4 can be set to max-

height, max-width, and the centered block can have vertical wrapping properties. Since the horizontal direction is inside the table-cell, max-width will be displayed directly, that is, the width will become larger.

5. display: inline-block

<style type="text/css">

.wrp5 {
    text-align: center;
    overflow: auto;
}
.box5 {
    display: inline-block;
    vertical-align: middle;
    width: auto;
    height: auto;
    max-width: 90%;
    max-height: 90%;
}
.wrp5:after {
    content: &#39;&#39;;
    display: inline-block;
    vertical-align: middle;
    height: 100%;
    margin-left: -0.25em;
    /* To offset spacing. May vary by font */
}
</style>
<div class="wrp wrp5">

<div class="box box5">
    <h3 id="完全居中方案五">完全居中方案五:</h3>
    <h3 id="开发工具-nbsp-nbsp-WeX-nbsp-nbsp-高性能轻架构-开源免费-跨端-可视化">开发工具 【 WeX5 】: 高性能轻架构、开源免费、跨端、可视化</h3>
</div>
</div>

Effect:

Introduction to 6 ways to achieve perfect vertical and horizontal centering using CSS

Implementation principle: Principle: Use inline-block's vertical-align: middle to align the after pseudo-element. The height of the after pseudo-element is the same as the parent object, thus achieving alignment in the height direction. Option 5 achieves better results. The size of the center block can be used for wrapping and adaptive content, and the compatibility is also quite good. The disadvantage is that horizontal centering requires consideration of the white space in the inline-block interval (the legacy of code line breaks.). The centered block in Scheme 4 can set max-height and max-width, and the centered block can be adaptive in both horizontal and vertical directions.

6. display: flex-box

<style type="text/css">

.wrp6 {
    display: -webkit-flex;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-box;
    display: flex;
    -webkit-box-align: center;
    -moz-box-align: center;
    -ms-flex-align: center;
    -webkit-align-items: center;
    align-items: center;
    -webkit-box-pack: center;
    -moz-box-pack: center;
    -ms-flex-pack: center;
    -webkit-justify-content: center;
    justify-content: center;
}

.box6 {
    width: auto;
    height: auto;
    max-width: 90%;
    max-height: 90%;
}
</style>
<div class="wrp wrp6">

<div class="box box6">
    <h3 id="完全居中方案六">完全居中方案六:</h3>
    <h3 id="开发工具-nbsp-nbsp-WeX-nbsp-nbsp-高性能轻架构-开源免费-跨端-可视化">开发工具 【 WeX5 】: 高性能轻架构、开源免费、跨端、可视化</h3>
</div>
</div>

Effect:

Introduction to 6 ways to achieve perfect vertical and horizontal centering using CSS

Implementation principle: flexbox layout. This is the ultimate layout method, specially designed to solve various layout and positioning problems! Advantages: It can solve various arrangement and layout problems, and the implementation method is consistent with human cognition. Disadvantages: Some old browsers on PC do not have high support.

The above is the detailed content of Introduction to 6 ways to achieve perfect vertical and horizontal centering using 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
Simulating Mouse MovementSimulating Mouse MovementApr 22, 2025 am 11:45 AM

If you've ever had to display an interactive animation during a live talk or a class, then you may know that it's not always easy to interact with your slides

Powering Search With Astro Actions and Fuse.jsPowering Search With Astro Actions and Fuse.jsApr 22, 2025 am 11:41 AM

With Astro, we can generate most of our site during our build, but have a small bit of server-side code that can handle search functionality using something like Fuse.js. In this demo, we’ll use Fuse to search through a set of personal “bookmarks” th

Undefined: The Third Boolean ValueUndefined: The Third Boolean ValueApr 22, 2025 am 11:38 AM

I wanted to implement a notification message in one of my projects, similar to what you’d see in Google Docs while a document is saving. In other words, a

In Defense of the Ternary StatementIn Defense of the Ternary StatementApr 22, 2025 am 11:25 AM

Some months ago I was on Hacker News (as one does) and I ran across a (now deleted) article about not using if statements. If you’re new to this idea (like I

Using the Web Speech API for Multilingual TranslationsUsing the Web Speech API for Multilingual TranslationsApr 22, 2025 am 11:23 AM

Since the early days of science fiction, we have fantasized about machines that talk to us. Today it is commonplace. Even so, the technology for making

Jetpack Gutenberg BlocksJetpack Gutenberg BlocksApr 22, 2025 am 11:20 AM

I remember when Gutenberg was released into core, because I was at WordCamp US that day. A number of months have gone by now, so I imagine more and more of us

Creating a Reusable Pagination Component in VueCreating a Reusable Pagination Component in VueApr 22, 2025 am 11:17 AM

The idea behind most of web applications is to fetch data from the database and present it to the user in the best possible way. When we deal with data there

Using 'box shadows' and clip-path togetherUsing 'box shadows' and clip-path togetherApr 22, 2025 am 11:13 AM

Let's do a little step-by-step of a situation where you can't quite do what seems to make sense, but you can still get it done with CSS trickery. In this

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.