search
HomeWeb Front-endCSS TutorialSummary of 10 ways to achieve horizontal and vertical centering with CSS worth collecting

This article brings you a summary of 10 ways to achieve horizontal and vertical centering in CSS that are worth collecting. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Mark the key points. This is a must-have interview question. Many interviewers like to ask this question. I have been asked it several times

Summary of 10 ways to achieve horizontal and vertical centering with CSS worth collecting

It seems very simple to achieve the effect of the above picture, but in fact there is a hidden secret. This article summarizes the following ways to achieve horizontal and vertical centering in CSS. This article will introduce them one by one.

Only centered elements Width and height apply

  • absolute negative margin

  • absolute margin auto

  • ##absolute calc

The centered element has variable width and height

  • absolute transform

  • lineheight

  • writing-mode

  • table

  • css-table

  • flex

  • #grid

absolute negative margin

In order to achieve the above effect, let’s do some preparatory work. Assume that the HTML code is as follows, a total of two elements, parent elements and child elements

<div>
    <div>123123</div>
</div>
wp is the class name of the parent element, box is the class name of the child element, because there is a difference between fixed width and variable width, size is used to indicate the specified width, the following are all The common code used for all effects is mainly to set the color and width and height

Note: This common code will not be repeated later, only the corresponding prompt will be given

/* 公共代码 */
.wp {
    border: 1px solid red;
    width: 300px;
    height: 300px;
}

.box {
    background: green;    
}

.box.size{
    width: 100px;
    height: 100px;
}
/* 公共代码 */
The percentage of absolute positioning is relative to the width and height of the parent element. This feature allows the child element to be displayed in the center, but absolute positioning is based on the upper left corner of the child element. The desired effect is that the center of the child element is displayed

In order to correct this problem, you can use the negative value of the margin. Negative margins can position the element in the opposite direction. By specifying the margin of the sub-element as a negative value that is half the width of the sub-element, the sub-element can be centered. , the css code is as follows

/* 此处引用上面的公共代码 */
/* 此处引用上面的公共代码 */

/* 定位代码 */
.wp {
    position: relative;
}
.box {
    position: absolute;;
    top: 50%;
    left: 50%;
    margin-left: -50px;
    margin-top: -50px;
}
This is my more commonly used method. This method is easier to understand and has good compatibility. The disadvantage is that you need to know the width and height of the child elements

Click to view the complete DEMO

absolute margin auto

This method also requires that the width and height of the centered element must be fixed. The HTML code is as follows

<div>
    <div>123123</div>
</div>
This method sets the distance in each direction. 0. At this time, if the margin is set to auto, it can be centered in all directions.

/* 此处引用上面的公共代码 */
/* 此处引用上面的公共代码 */

/* 定位代码 */
.wp {
    position: relative;
}
.box {
    position: absolute;;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}
This method is also very compatible. The disadvantage is that you need to know the width and height of the child elements

Click to view the complete DEMO

absolute calc

This method also requires that the width and height of the centered element must be fixed, so we add a size class to the box. The HTML code is as follows

<div>
    <div>123123</div>
</div>
Thanks CSS3 brings calculated properties. Since the percentage of top is based on the upper left corner of the element, then just subtract half of the width. The code is as follows

/* 此处引用上面的公共代码 */
/* 此处引用上面的公共代码 */

/* 定位代码 */
.wp {
    position: relative;
}
.box {
    position: absolute;;
    top: calc(50% - 50px);
    left: calc(50% - 50px);
}
The compatibility of this method depends on the compatibility of calc. Disadvantages Do you need to know the width and height of the child element

Click to view the complete DEMO

absolute transform

or absolute positioning, but this method does not require the child element to have a fixed width and height, so no more The size class is needed. The HTML code is as follows

<div>
    <div>123123</div>
</div>
To fix the absolute positioning problem, you can also use the new transform in CSS3. The translate attribute of transform can also set a percentage, which is relative to its own width and height, so It can be said that if translate is set to -50%, it can be centered. The code is as follows

/* 此处引用上面的公共代码 */
/* 此处引用上面的公共代码 */

/* 定位代码 */
.wp {
    position: relative;
}
.box {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
The compatibility of this method depends on the compatibility of translate2d

Click to view the complete DEMO

lineheight

Using the centering attribute of inline elements, you can also achieve horizontal and vertical centering. The HTML code is as follows

<div>
    <div>123123</div>
</div>
Set the box as an inline element through

text-align Achieve horizontal centering, but many students may not know that it can also be vertically centered through vertical-align, the code is as follows

/* 此处引用上面的公共代码 */
/* 此处引用上面的公共代码 */

/* 定位代码 */
.wp {
    line-height: 300px;
    text-align: center;
    font-size: 0px;
}
.box {
    font-size: 16px;
    display: inline-block;
    vertical-align: middle;
    line-height: initial;
    text-align: left; /* 修正文字 */
}
This method requires text to be placed in the child element The display is reset to the desired effect

Click to view the complete DEMO

writing-mode

Many students must not know it like me

writing-mode Attribute, thanks to teacher @张鑫兴 for the feedback. Simply put, writing-mode can change the display direction of text. For example, writing-mode can be used to change the display direction of text to vertical direction

<div>水平方向</div>
<div>垂直方向</div>
rrreeThe display effect is as follows:

.div2 {
    writing-mode: vertical-lr;
}
What’s more amazing is that all horizontal css attributes will become vertical attributes, such as

text-align, through writing-mode and text-align can achieve horizontal and vertical centering, but it is a little more troublesome

水平方向
垂
直
方
向
<div>
    <div>
        <div>123123</div>
    </div>
</div>
This method is a little complicated to implement and understand

Click View the complete DEMO

table

Tables used to be used for page layout, but no one does this anymore, but tables can also achieve horizontal and vertical centering, but it will add a lot of redundant code

/* 此处引用上面的公共代码 */
/* 此处引用上面的公共代码 */

/* 定位代码 */
.wp {
    writing-mode: vertical-lr;
    text-align: center;
}
.wp-inner {
    writing-mode: horizontal-tb;
    display: inline-block;
    text-align: center;
    width: 100%;
}
.box {
    display: inline-block;
    margin: auto;
    text-align: left;
}
The content in the tabel cell is naturally vertically centered. Just add a horizontal centering attribute.



    
        
            
        
    
                
123123
            
This method is too redundant in code and is not the correct usage of table

点击查看完整DEMO

css-table

css新增的table属性,可以让我们把普通元素,变为table元素的现实效果,通过这个特性也可以实现水平垂直居中

<div>
    <div>123123</div>
</div>

下面通过css属性,可以让p显示的和table一样

.wp {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.box {
    display: inline-block;
}

这种方法和table一样的原理,但却没有那么多冗余代码,兼容性也还不错

点击查看完整DEMO

flex

flex作为现代的布局方案,颠覆了过去的经验,只需几行代码就可以优雅的做到水平垂直居中

<div>
    <div>123123</div>
</div>
.wp {
    display: flex;
    justify-content: center;
    align-items: center;
}

目前在移动端已经完全可以使用flex了,PC端需要看自己业务的兼容性情况

点击查看完整DEMO

grid

感谢@一丝姐 反馈的这个方案,css新出的网格布局,由于兼容性不太好,一直没太关注,通过grid也可以实现水平垂直居中

<div>
    <div>123123</div>
</div>
.wp {
    display: grid;
}
.box {
    align-self: center;
    justify-self: center;
}

代码量也很少,但兼容性不如flex,不推荐使用

点击查看完整DEMO

总结

下面对比下各个方式的优缺点,肯定又双叒叕该有同学说回字的写法了,简单总结下

  • PC端有兼容性要求,宽高固定,推荐absolute + 负margin

  • PC端有兼容要求,宽高不固定,推荐css-table

  • PC端无兼容性要求,推荐flex

  • 移动端推荐使用flex

小贴士:

方法 居中元素定宽高固定 PC兼容性 移动端兼容性
absolute + 负margin ie6+, chrome4+, firefox2+ 安卓2.3+, iOS6+
absolute + margin auto ie6+, chrome4+, firefox2+ 安卓2.3+, iOS6+
absolute + calc ie9+, chrome19+, firefox4+ 安卓4.4+, iOS6+
absolute + transform ie9+, chrome4+, firefox3.5+ 安卓3+, iOS6+
writing-mode ie6+, chrome4+, firefox3.5+ 安卓2.3+, iOS5.1+
lineheight ie6+, chrome4+, firefox2+ 安卓2.3+, iOS6+
table ie6+, chrome4+, firefox2+ 安卓2.3+, iOS6+
css-table ie8+, chrome4+, firefox2+ 安卓2.3+, iOS6+
flex ie10+, chrome4+, firefox2+ 安卓2.3+, iOS6+
grid ie10+, chrome57+, firefox52+ 安卓6+, iOS10.3+

最近发现很多同学都对css不够重视,这其实是不正确的,比如下面的这么简单的问题都有那么多同学不会,我也是很无语

<div>123</div>
<div>123</div>
.red {
    color: red
}

.blue {
    color: blue
}

相关推荐:

CSS实现div水平垂直居中的五种方法

css 实现DIV水平垂直居中于屏幕

The above is the detailed content of Summary of 10 ways to achieve horizontal and vertical centering with CSS worth collecting. 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
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment