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
Draggin' and Droppin' in ReactDraggin' and Droppin' in ReactApr 17, 2025 am 11:52 AM

The React ecosystem offers us a lot of libraries that all are focused on the interaction of drag and drop. We have react-dnd, react-beautiful-dnd,

Fast SoftwareFast SoftwareApr 17, 2025 am 11:49 AM

There have been some wonderfully interconnected things about fast software lately.

Nested Gradients with background-clipNested Gradients with background-clipApr 17, 2025 am 11:47 AM

I can't say I use background-clip all that often. I'd wager it's hardly ever used in day-to-day CSS work. But I was reminded of it in a post by Stefan Judis,

Using requestAnimationFrame with React HooksUsing requestAnimationFrame with React HooksApr 17, 2025 am 11:46 AM

Animating with requestAnimationFrame should be easy, but if you haven’t read React’s documentation thoroughly then you will probably run into a few things

Need to scroll to the top of the page?Need to scroll to the top of the page?Apr 17, 2025 am 11:45 AM

Perhaps the easiest way to offer that to the user is a link that targets an ID on the element. So like...

The Best (GraphQL) API is One You WriteThe Best (GraphQL) API is One You WriteApr 17, 2025 am 11:36 AM

Listen, I am no GraphQL expert but I do enjoy working with it. The way it exposes data to me as a front-end developer is pretty cool. It's like a menu of

Weekly Platform News: Text Spacing Bookmarklet, Top-Level Await, New AMP Loading IndicatorWeekly Platform News: Text Spacing Bookmarklet, Top-Level Await, New AMP Loading IndicatorApr 17, 2025 am 11:26 AM

In this week's roundup, a handy bookmarklet for inspecting typography, using await to tinker with how JavaScript modules import one another, plus Facebook's

Various Methods for Expanding a Box While Preserving the Border RadiusVarious Methods for Expanding a Box While Preserving the Border RadiusApr 17, 2025 am 11:19 AM

I've recently noticed an interesting change on CodePen: on hovering the pens on the homepage, there's a rectangle with rounded corners expanding in the back.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

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.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment