前端面试中CSS水平垂直居中的方法,你知道吗?

  要论在前端面试中CSS常考的题目,水平垂直居中一定有姓名。如果是平时不注意写样式的初学者,这道看似简单的问题也不是很容易回答,现整理了一下CSS水平垂直居中的方法,可作为前端面试准备资料。

  要想做水平垂直居中,我们先准备两个盒子,大盒子里面套一个小盒子,这个时候我们要想css设置垂直居中,套在里面的要做水平垂直居中的小盒子的宽高我们知道吗?宽高知道或者不知道,做水平垂直居中的方法一样吗?答案是不一样的,下面就要分情况讨论了,各提供了两种解决方案。

  〇、先准备一下盒子,也就是html的内容:

  

  1. 水平垂直居中块级元素(已知宽高)
  2. 水平垂直居中块级元素(已知宽高)
  3. 水平垂直居中块级元素(未知宽高)
  4. 水平垂直居中块级元素(未知宽高)

  一、已知小盒子宽高方法1:子绝父相。子盒子的top、bottom、left、right为0css设置垂直居中,margin为auto

   #father1{

  1. width: 600px;
  2. height: 300px;
  3. position: relative;
  4. background-color: aquamarine;
  5. margin-bottom: 10px;
  6. }
  7. #son1{
  8. position: absolute;
  9. width: 100px;
  10. height: 80px;
  11. top: 0;
  12. bottom: 0;
  13. left: 0;
  14. right: 0;
  15. margin: auto;
  16. background-color: beige;

  CSS-水平垂直居中

  方法2:子绝父相。子盒子的top、left为50%,margin-top为负的子盒子高度的一半,margin-left为负的子盒子宽度的一半

   #father2{

  1. width: 600px;
  2. height: 300px;
  3. position: relative;
  4. background-color: blueviolet;
  5. margin-bottom: 10px;
  6. }
  7. #son2{
  8. position: absolute;
  9. width: 100px;
  10. height: 80px;
  11. left: 50%;
  12. top: 50%;
  13. margin-left: -50px; /* #son2盒子宽度的一半的负数*/
  14. margin-top: -40px; /* #son2盒子高度的一半的负数*/
  15. background-color: chartreuse;

  CSS-水平垂直居中

  二、未知小盒子宽高方法1:子绝父相。子盒子的top、left为50% ,transform: translateX(-50%) translateY(-50%)

   #father3{

  1. width: 600px;
  2. height: 300px;
  3. background-color: coral;
  4. position: relative;
  5. margin-bottom: 10px;
  6. }
  7. #son3{
  8. position: absolute;
  9. left: 50%;
  10. top: 50%;
  11. transform: translateX(-50%) translateY(-50%);
  12. background-color: cornsilk;

  CSS-水平垂直居中

  方法2:弹性布局。设置justify-items和align-items为center

   #father4{

  1. width: 600px;
  2. height: 300px;
  3. display: flex;
  4. justify-content: center;
  5. align-items: center;
  6. background-color: darkred;
  7. }
  8. #son4{
  9. background-color: darkgrey;

  CSS-水平垂直居中

  【作者水平有限,欢迎大家在评论区交流指正~】

  程序员灯塔

文章由官网发布,如若转载,请注明出处:https://www.veimoz.com/1460
0 评论
810

发表评论

!