水平居中的几种方式

来源:互联网 发布:linux 开发工具 编辑:程序博客网 时间:2024/06/06 02:05

方式一:水平居中:给div设置一个宽度,然后添加margin:0 auto属性

div {
                width: 200px;
                height: 300px;
                margin: 0 auto;
                background-color: pink;
            }

方式二:让绝对定位的div居中

div {
                position: absolute;
                width: 300px;
                height: 300px;
                margin: auto;
                top: 0;
                left: 0;
                bottom: 0;
                right: 0;
                background-color: pink;
            }

方式三:确定容器的宽高 宽500px 高 300px 的层
              设置层的外边距

div {
                position: absolute;
                width: 500px;
                height: 300px;
                top: 50%;
                left: 50%;
                margin: -150px 0 0 -250px;
                background-color: pink;   
            }

方式四:未知容器的宽高,利用 `transform` 属性

div {
                position: absolute;
                width: 500px;
                height: 300px;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background-color: pink;
            }

以上经验和代码整理来至:https://github.com/markyun/My-blog/tree/master/Front-end-Developer-Questions/Questions-and-Answers

0 0
原创粉丝点击