
盒子居中的几种常用方法
发布日期:2021-05-07 18:31:13
浏览次数:18
分类:技术文章
本文共 2045 字,大约阅读时间需要 6 分钟。
CSS 盒子居中的六种常用方法
-------------------------------------最传统的方法
.wrapper{ position: relative; width: 400px; height: 400px; background-color: aqua; } .box{ position: absolute; width: 100px; height: 100px; background-color: red; left: 50%; top:50%; margin-left: -50px; margin-top: -50px; }
-------------------------------------利用transform
.wrapper{ position: relative; width: 400px; height: 400px; background-color: aqua; } .box{ position: absolute; width: 100px; height: 100px; background-color: red; left: 50%; top:50%; transform: translate(-50%,-50%); }
-------------------------------------利用flex(弹性布局)
.wrapper{ display: flex; width: 400px; height: 400px; background-color: aqua; justify-content: center; align-items: center; } .box{ width: 100px; height: 100px; background-color: red; }
---------------------------------利用justify-content: space-around;(用的极少)
.wrapper{ display: flex; width: 400px; height: 400px; background-color: aqua; /*justify-content: space-between; (左右两边对齐)*/ justify-content: space-around; align-items: center; } .box{ width: 100px; height: 100px; background-color: red; }
---------------------------------拓展
justify-content: center; 水平居中 justify-content: space-between; 两端对齐 justify-content: space-around; 盒子四周距离相等(可以用来居中) justify-content: flex-start; 左端对齐 justify-content: flex-end; 右端对齐---------------------------------新学的
.wrapper{ display: flex; width: 200px; height: 400px; background-color: aqua; position: relative; } .box{ width: 100px; height: 100px; background-color: red; position: absolute; margin: auto; top: 0; left: 0; right: 0; bottom: 0; }
---------------------------------利用display: table-cell; vertical-align: middle;
.wrapper{ display: flex; width: 400px; height: 400px; background-color: aqua; display: table-cell; vertical-align: middle; } .box{ width: 100px; height: 100px; background-color: red; margin: auto; }
发表评论
最新留言
路过按个爪印,很不错,赞一个!
[***.219.124.196]2025年04月08日 19时46分43秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
实现一个简易Vue(三)Compiler
2019-03-04
仿小米商城(上)
2019-03-04
仿小米商城(下)
2019-03-04
【30】kotlin 闭包
2019-03-04
文件md5怎么会变化
2019-03-04
好玩的editText
2019-03-04
自动安装服务2
2019-03-04
android 用action拦截打电话界面
2019-03-04
2019年一个程序员的回顾与成长计划
2019-03-04
js的各种数据类型判断(in、hasOwnProperty)
2019-03-04
严格模式、混杂模式与怪异模式
2019-03-04
一篇文章带你搞定 Java 中字符流的基本操作(Write / Read)
2019-03-04
HTML 和 CSS 简单实现注册页面
2019-03-04
(SpringMVC)springMVC.xml 和 web.xml
2019-03-04
Oracle 学习一篇文章就够了(珍藏版)
2019-03-04
(LeetCode)Java 求解搜索旋转排序数组
2019-03-04
(模拟数组)Java 求解螺旋矩阵 II
2019-03-04
Python学习:字符串
2019-03-04