Home Web Front-end HTML Tutorial CSS之水平垂直居中_html/css_WEB-ITnose

CSS之水平垂直居中_html/css_WEB-ITnose

Jun 24, 2016 am 11:22 AM

在css的世界里,如果我们想让一个块级元素水平居中,想必大家都知道利用margin:0 auto;嘛,这样就可以让块级元素在它的父元素中水平居中了。

列如这样:

<!DOCTYPE html>    <head>        <title>center</title>        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>        <style>                .parent {                width:50%;                height:100px;                border:1px solid black;                position:relative;            }            .child {                margin:0 auto;                width:50px;                height:50px;                background:#22B14C;            }            </style>    </head>    <body>        <div class="parent">               <div class="child">                         </div>        </div>    </body></html>
Copy after login

运行效果图如下,绿色方块水平居中于它的父元素

咦,那么问题来了,我们想要绿色方块垂直居中或者水平垂直居中呢?

是不是只要设置margin:auto 0;或margin:auto;就可以了呢?

曾经我也是这么以为的,因为设置margin:0 auto;可以水平居中嘛。

但是垂直居中就不是这么回事啦。

在普通文档流中,倘若你设置margin:auto,其实浏览器解析时,会理解为margin:0 auto;

(将margin-top和margin-bottom设置为0,而margin-left和margin-right设置为左右自适应)。

摘自W3.org

如果你心存顾虑,可以将上面demo中的margin:0 auto;换成margin:auto;,运行后的结果是一样的。

咦,那如果我们现在想让块级元素垂直居中呢,如何处理?

方法一:

将元素设置为绝对定位absolute,这样就可以让元素脱离普通文档流,且absolute有一特性:会将元素的display设置为block。

然后,再设置绝对定位的坐标(left,top,right,bottom)为0,这样会使浏览器为绝对定位包裹一层新的盒子模型。

再结合margin,就可以你想水平居中(margin:0 auto;)就居中,垂直居中(margin:auto 0;)就居中了,水平垂直居中(margin:auto;)也完美。

下面列举的demo为‘水平垂直居中’:

<!DOCTYPE html>    <head>        <title>center</title>        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>        <style>                .parent {                width:50%;                height:100px;                border:1px solid black;                position:relative;            }            .child {                margin: auto;                position: absolute;                top:0;                left:0;                bottom:0;                right:0;                width:50px;                height:50px;                background:#22B14C;            }            </style>    </head>    <body>        <div class="parent">                   <div class="child">                         </div>        </div>    </body></html>
Copy after login

PS:position:fixed也可以脱离文档流,so它和absolute是一样儿滴,区别就是fixed是相对于浏览器窗口进行定位的。

方法二:

方法一是通过改变元素的文档流,那么除开改变它的文档流呢?

那我们就另辟蹊径,计算元素的宽高嘛。

么子意思?

以‘垂直居中’举例,倘若我们有个子元素child,需要垂直居中于它的父元素parent。如下:

图一

那么首先我们得将子元素child以父元素的顶点(top,left=0 如上图所示),往下和右移动父元素宽高的50%;如下图所示:

图二

再将子元素Child以parent中心点,往上和左移动自身元素宽高的50%,就垂直居中啦,如下图所示:

图三

好了,这个流程我们是理清楚了,那用CSS应该怎么实现呢?

列举2个:

(1)、 margin + absolute

设置child为absolute,将其top、right皆为50%,那么就使得子元素层显上图图二的情况;

再将元素的margin-top,margin-right设置为-50%,那么就可以实现垂直居中啦。

示例代码如下:

<!DOCTYPE html>    <head>        <title>center</title>        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>        <style>                .parent {                width:50%;                height:100px;                border:1px solid black;                position:relative;            }            .child {                position:absolute;                width:50px;                height:50px;                top:50%;                left:50%;                margin-top:-25px;                margin-left:-25px;                background:#22B14C;            }                 </style>    </head>    <body>        <div class="parent">            <div class="child">                             </div>        </div>    </body></html>
Copy after login

(2)、 translate + absolute

设置child为absolute,将其top、right皆为50%,那么就使得子元素层显上图图二的情况;

再通过translate将元素移动50%,50%,也可以得到图三,实现垂直居中。

示例代码如下:

<!DOCTYPE html>    <head>        <title>center</title>        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>        <style>                .parent {                width:50%;                height:100px;                border:1px solid black;                position:relative;            }            .child {                position:absolute;                width:50px;                height:50px;                top:50%;                left:50%;                <!--渐进增强-->                -webkit-transform: translate(-50%,-50%);                    -ms-transform: translate(-50%,-50%);                        transform: translate(-50%,-50%);                background:#22B14C;            }                 </style>    </head>    <body>        <div class="parent">            <div class="child">                             </div>                    </div>    </body></html>
Copy after login

方法三:

利用table-cell属性就可以轻松实现。

将父元素变为table-cell,从而可以使用table的属性vertical-align:middle,使元素垂直居中,再将子元素margin:0 atuo;就可以实现水平居中咯。

PS:table-cell必须包含在display:table元素中,table-cell是属于table滴嘛。

示例代码如下:

<!DOCTYPE html>    <head>        <title>center</title>        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>        <style>                .root {                width:50%;                height:100px;                border:1px solid black;                display:table;            }            .parent {                display:table-cell;                vertical-align:middle;            }             .child {                width:50px;                height:50px;                background:#22B14C;                margin:0 auto;            }                    </style>    </head>    <body>        <div class="root">            <div class="parent">                 <div class="child"></div>            </div>        </div>    </body></html>
Copy after login

好了,css之垂直水平居中就算完了(弹性布局Flex不在本篇讨论范畴)。

晚安,everyone~

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

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the purpose of the <progress> element? What is the purpose of the <progress> element? Mar 21, 2025 pm 12:34 PM

The article discusses the HTML &lt;progress&gt; element, its purpose, styling, and differences from the &lt;meter&gt; element. The main focus is on using &lt;progress&gt; for task completion and &lt;meter&gt; for stati

What is the purpose of the <datalist> element? What is the purpose of the <datalist> element? Mar 21, 2025 pm 12:33 PM

The article discusses the HTML &lt;datalist&gt; element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

What are the best practices for cross-browser compatibility in HTML5? What are the best practices for cross-browser compatibility in HTML5? Mar 17, 2025 pm 12:20 PM

Article discusses best practices for ensuring HTML5 cross-browser compatibility, focusing on feature detection, progressive enhancement, and testing methods.

What is the purpose of the <meter> element? What is the purpose of the <meter> element? Mar 21, 2025 pm 12:35 PM

The article discusses the HTML &lt;meter&gt; element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates &lt;meter&gt; from &lt;progress&gt; and ex

How do I use HTML5 form validation attributes to validate user input? How do I use HTML5 form validation attributes to validate user input? Mar 17, 2025 pm 12:27 PM

The article discusses using HTML5 form validation attributes like required, pattern, min, max, and length limits to validate user input directly in the browser.

What is the viewport meta tag? Why is it important for responsive design? What is the viewport meta tag? Why is it important for responsive design? Mar 20, 2025 pm 05:56 PM

The article discusses the viewport meta tag, essential for responsive web design on mobile devices. It explains how proper use ensures optimal content scaling and user interaction, while misuse can lead to design and accessibility issues.

What is the purpose of the <iframe> tag? What are the security considerations when using it? What is the purpose of the <iframe> tag? What are the security considerations when using it? Mar 20, 2025 pm 06:05 PM

The article discusses the &lt;iframe&gt; tag's purpose in embedding external content into webpages, its common uses, security risks, and alternatives like object tags and APIs.

Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Apr 04, 2025 pm 11:54 PM

GiteePages static website deployment failed: 404 error troubleshooting and resolution when using Gitee...

See all articles