前端css子盒子居中方法

283 阅读1分钟

前端css中的子盒自四种居中方法.

第一种

用定位position: absolute和position: relative子绝父相, 子盒子移动父子高度和宽度的一半,再移动自身高度和宽度的一半.代码如下

 `<!DOCTYPE html>
  <html lang="en">

  <head>
 <meta charset="UTF-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Document</title>
 <style>
    .box {
        position: relative;
        width: 500px;
        height: 500px;
        border: 1px solid #000;
        margin: 100px auto;
    }
    
    .box1 {
        position: absolute;
        top: 50%;
        left: 50%;
        margin-left: -50px;
        margin-top: -50px;
        width: 100px;
        height: 100px;
        background-color: aqua;
    }
</style>
`

Snipaste_2022-04-23_20-47-17.png 第二种

同样先是用定位子绝父相,先移动父盒子高度和宽度的一半,然后用transform的translate属性移动自身高度宽度的一半.代码如下

      `<!DOCTYPE html>
        <html lang="en">

        <head>
    <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Document</title>
   <style>
    .box {
        position: relative;
        width: 500px;
        height: 500px;
        border: 1px solid #000;
        margin: 100px auto;
    }
    
    .box1 {
        position: absolute;
        top: 50%;
        left: 50%;
        width: 100px;
        height: 100px;
        transform: translate(-50%, -50%);
        background-color: aqua;
    }
</style>
`

第三种

先定位子绝父相,然后子盒子的top,left,right,bottom的值全部设为0,margin值为auto,上代码

   `<!DOCTYPE html>
      <html lang="en">

           <head>
           <meta charset="UTF-8">
         <meta http-equiv="X-UA-Compatible" content="IE=edge">
         <meta name="viewport" content="width=device-width, initial-scal                e=1.0">
     <   title>Document</title>
   <style>
    .box {
        position: relative;
        width: 500px;
        height: 500px;
        border: 1px solid #000;
        margin: 100px auto;
    }
    
    .box1 {
        position: absolute;
        top: 50%;
        left: 50%;
        width: 100px;
        height: 100px;
        transform: translate(-50%, -50%);
        background-color: aqua;
    }
</style>
`

第四种

是用flex布局,给父盒自设置display: flex,然后给父盒子添加justify-content: center垂直居中 align-items: center;水平居中 flex布局的属性都是父盒子设置,上代码

`<!DOCTYPE html>
 <html lang="en">

  <head>
 <meta charset="UTF-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Document</title>
 <style>
    .box {
        display: flex;
        width: 500px;
        height: 500px;
        background-color: pink;
        margin: 100px auto;
        justify-content: center;
        align-items: center;
    }
    
    span {
        width: 100px;
        height: 100px;
        background-color: blue;
        transform: rotate(45deg);
    }
</style>
`