《一课全面掌握主流CSS布局》笔记之水平居中

889 阅读2分钟

前言

最近在学慕课网的一门课程《一课全面掌握主流CSS布局》,空闲之余将课程所学内容粗略地做一下笔记总结。

一、水平居中的三种方式

方法一:text-align: center + display: inline-block;

<html>
    <head>
        <title>水平居中1</title>
        <style>
            #parent{
                text-align: center;
            }
            
            #child{
                display: inline-block;
                width: 200px;
                height: 200px;
                background: lightyellow;
            }
        </style>
    </head>
    <body>
        <div id="parent">
            <div id="child">
            </div>
        </div>
    </body>
</html>
解析:

这种居中方式的关键点在于 text-align: center ① 以及 display: inline-block ②这两个属性。

① 主要是针对行内元素以及行内块级元素进行居中

② 而使div#child表现为行内块级元素


方法二:display: block | table + margin: * auto; * 表示90px、90%、49vh、34vw等任意有效长度单位或auto

<html>
    <head>
        <title>水平居中2</title>
        <style>
            #child{
                display: block; /*在当前div其实可省略,仅做展示*/
                /*display: table;*/
                margin: 0 auto;
                width: 200px;
                height: 200px;
                background: lightyellow;
            }
        </style>
    </head>
    <body>
        <div id="parent">
            <div id="child">
            </div>
        </div>
    </body>
</html>

解析

这种居中方式的关键点在于 display: block | table ① 以及 margin: 0 auto ②这两个属性。

② 可针对块级元素进行水平居中 ps:margin对行内块级元素使用无效 ① 使元素变成块级元素


方法三:定位 + transform

<html>
    <head>
        <title>水平居中3</title>
        <style>
            #parent{
                position: relative;
            }
            #child{
                position: absolute;
                left: 50%;
                transform: translateX(-50%);
                margin: 0 auto;
                width: 200px;
                height: 200px;
                background: lightyellow;
            }
        </style>
    </head>
    <body>
        <div id="parent">
            <div id="child">
            </div>
        </div>
    </body>
</html>

解析

这种居中方式的关键点在于 position: absolute; left: 50%; ① 以及 transform: translateX(-50%); ②这两个属性。

在①的作用下,#child元素的左边线在#parent的正中间。这是加入②的代码片段,可以使#child元素向左偏移自身的50%宽度,故实现水平居中。