博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
CSS的四种方式实现水平居中
阅读量:3963 次
发布时间:2019-05-24

本文共 1138 字,大约阅读时间需要 3 分钟。

			
四种方式实现水平居中
/* flex弹性布局 	 父盒子加 弹性元素display: flex 导致的是子盒子的垂直居中*/.box1{
background-color: gray; width: 600px; height: 600px; display: flex; align-items: center; justify-content: center;}.box2{
background-color: hotpink; width: 200px; height: 200px;}
/* 绝对定位 '子绝父相' */.box1{
position: relative; background-color: gray; width: 600px; height: 600px;}.box2{
position: absolute; background-color: hotpink; width: 200px; height: 200px; top: 50%; left: 50%; margin-top: -100px; margin-left: -100px;}
/* 绝对定位 margin: auto */.box1{
position: relative; background-color: gray; width: 600px; height: 600px;}.box2{
position: absolute; background-color: hotpink; width: 200px; height: 200px; /* 设置四个方向为0,就像四个方向有相同的力在拉这个盒子,配上margin:auto让这个盒子的位置保持中立,来使盒子处于正中心 */ top: 0; left: 0; bottom: 0; right: 0; margin: auto;}
/* 绝对定位 位偏移 */.box1{
position: relative; background-color: gray; width: 600px; height: 600px;}.box2{
position: absolute; background-color: hotpink; width: 200px; height: 200px; top: 50%; left: 50%; /* 平移,参考自己的位置来平移 */ transform: translate(-50%, -50%);}

四种方式效果相同,各有优缺,如下图

在这里插入图片描述

转载地址:http://yqzki.baihongyu.com/

你可能感兴趣的文章
内部类
查看>>
固化分组和占有量词
查看>>
去除首尾空白字符
查看>>
去掉文件名中的路径
查看>>
Spring Batch Step 流程
查看>>
动态代理
查看>>
如何写出高效的正则表达式
查看>>
多个 ZooKeeper 服务器的例子
查看>>
正则表达式
查看>>
Java I/O
查看>>
序列化
查看>>
Perl 精萃
查看>>
Perl 简介
查看>>
Perl 注释
查看>>
数据类型之标量
查看>>
调试 Perl 脚本
查看>>
增强的for循环语句
查看>>
方法的可变参数
查看>>
静态导入
查看>>
java 泛型
查看>>