一个div 通向垂直居中的n种罗马大道

一个固定宽高的div

flex布局

html:

<div class="box">
  <div class="box1"></div>
</div>

css:
    .box{
      /* 方法一 */
      width:200px;
      height:200px;
      border: 1px solid red;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .box1{
       width:100px;
       height:100px;
       background-color:yellow;
    }
复制代码

绝对定位+负margin布局

.box{
  /* 方法一 */
  width:200px;
  height:200px;
  border: 1px solid red;
  position: relative;
}
.box1{
  width:100px;
  height:100px;
  position: absolute;
  left:50%;
  top:50%;
  margin-left:-50px;
  margin-right:-50px;
}
复制代码

绝对定位+transform

.box{
  /* 方法一 */
  width:200px;
  height:200px;
  border: 1px solid red;
  position: relative;
}
.box1{
  width:100px;
  height:100px;
  position: absolute;
  left:50%;
  top:50%;
  transform: translate(-50%, -50%); 
}
复制代码

绝对定位+left/top/right/bottom

.box{
  /* 方法一 */
  width:200px;
  height:200px;
  border: 1px solid red;
  position: relative;
}
.box1{
  width:100px;
  height:100px;
  position: absolute;
  left:0;
  top:0;
  bottom:0;
  right:0;
  margin:auto;
  background-color:yellow;
}
复制代码

grid 布局

.box{
  /* 方法一 */
  width:200px;
  height:200px;
  border: 1px solid red;
  display:grid;
}
.box1{
  width:100px;
  height:100px;
  position: absolute;
  left:0;
  top:0;
  bottom:0;
  right:0;
  margin:auto;
  background-color:yellow;
}
复制代码

一个不定宽高的div

flex布局

html:
<div class="box">
  <div class="box1">这是一个测试的div</div>
</div>
css:
.box{
  /* 方法一 */
  width:200px;
  height:200px;
  border: 1px solid red;
  display:flex;
  justify-content: center;
  align-items: center;
}
.box1{
  background-color:yellow;
}
复制代码

图片.png

绝对定位+transform

html:
<div class="box">
  <div class="box1">这是一个测试的div</div>
</div>
css:
.box{
  /* 方法一 */
  width:200px;
  height:200px;
  border: 1px solid red;
  position: relative;  
}
.box1{
  position:absolute;
  left:50%;
  top:50%;
  transform: translate(-50%, -50%);
  background-color:yellow;
}
复制代码

flex 变异布局

html:
<div class="box">
  <div class="box1">这是一个测试的div</div>
</div>
css:
.box{
  /* 方法一 */
  width:200px;
  height:200px;
  border: 1px solid red;
  display:flex;
}
.box1{
  margin:auto;
  background-color:yellow;
}
复制代码

图片.png

grid+ flex布局

html:
<div class="box">
  <div class="box1">这是一个测试的div</div>
</div>
css:
.box{
  /* 方法一 */
  width:200px;
  height:200px;
  border: 1px solid red;
  display:grid;
}
.box1{
  justify-self: center;
  align-self: center;
  background-color:yellow;
}
复制代码

grid+ margin布局

html:
<div class="box">
  <div class="box1">这是一个测试的div</div>
</div>
css:
.box{
  /* 方法一 */
  width:200px;
  height:200px;
  border: 1px solid red;
  display:grid;
}
.box1{
  margin:auto;
  background-color:yellow;
}
复制代码

如果你觉得不错,记得给小姐姐点个赞!感谢

图片.png

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享