前端面试中CSS水平垂直居中的方法,你知道吗?
要论在前端面试中CSS常考的题目,水平垂直居中一定有姓名。如果是平时不注意写样式的初学者,这道看似简单的问题也不是很容易回答,现整理了一下CSS水平垂直居中的方法,可作为前端面试准备资料。
要想做水平垂直居中,我们先准备两个盒子,大盒子里面套一个小盒子,这个时候我们要想css设置垂直居中,套在里面的要做水平垂直居中的小盒子的宽高我们知道吗?宽高知道或者不知道,做水平垂直居中的方法一样吗?答案是不一样的,下面就要分情况讨论了,各提供了两种解决方案。
〇、先准备一下盒子,也就是html的内容:
-
- 水平垂直居中块级元素(已知宽高)
-
-
-
-
- 水平垂直居中块级元素(已知宽高)
-
-
-
-
- 水平垂直居中块级元素(未知宽高)
-
-
-
-
- 水平垂直居中块级元素(未知宽高)
-
-
一、已知小盒子宽高方法1:子绝父相。子盒子的top、bottom、left、right为0css设置垂直居中,margin为auto
#father1{
- width: 600px;
- height: 300px;
- position: relative;
- background-color: aquamarine;
- margin-bottom: 10px;
- }
- #son1{
- position: absolute;
- width: 100px;
- height: 80px;
- top: 0;
- bottom: 0;
- left: 0;
- right: 0;
- margin: auto;
- background-color: beige;
-
方法2:子绝父相。子盒子的top、left为50%,margin-top为负的子盒子高度的一半,margin-left为负的子盒子宽度的一半
#father2{
- width: 600px;
- height: 300px;
- position: relative;
- background-color: blueviolet;
- margin-bottom: 10px;
- }
- #son2{
- position: absolute;
- width: 100px;
- height: 80px;
- left: 50%;
- top: 50%;
- margin-left: -50px; /* #son2盒子宽度的一半的负数*/
- margin-top: -40px; /* #son2盒子高度的一半的负数*/
- background-color: chartreuse;
-
二、未知小盒子宽高方法1:子绝父相。子盒子的top、left为50% ,transform: translateX(-50%) translateY(-50%)
#father3{
- width: 600px;
- height: 300px;
- background-color: coral;
- position: relative;
- margin-bottom: 10px;
- }
- #son3{
- position: absolute;
- left: 50%;
- top: 50%;
- transform: translateX(-50%) translateY(-50%);
- background-color: cornsilk;
-
方法2:弹性布局。设置justify-items和align-items为center
#father4{
- width: 600px;
- height: 300px;
- display: flex;
- justify-content: center;
- align-items: center;
- background-color: darkred;
- }
- #son4{
- background-color: darkgrey;
-
【作者水平有限,欢迎大家在评论区交流指正~】
程序员灯塔
文章由官网发布,如若转载,请注明出处:https://www.veimoz.com/1460
0 评论
810
发表评论
热门文章
自媒体博客Spimes主题45w 阅读
Spimes主题专为博客、自媒体、资讯类的网站设计....
Splity博客双栏主题15w 阅读
仿制主题,Typecho博客主题,昼夜双版设计,可....
vCard主题个人简历主题13w 阅读
一款个人简历主题,可以简单搭建一下,具体也比较简单....
Spzac个人资讯下载类主题12w 阅读
用于作品展示、资源下载,行业垂直性网站、个人博客,....
热评文章
自媒体博客Spimes主题424 评论
Splity博客双栏主题191 评论
Spzac个人资讯下载类主题89 评论
Splinx博客图片主题35 评论
Spzhi知识付费社区主题34 评论
三栏清新博客S_blog主题31 评论
vCard主题个人简历主题29 评论
Pure轻简主题29 评论
chenyu
4月7日
能不能支持deepseek