元素水平垂直居中

基本html
<div id="box">
<div id="content">
  <div id="box1">1</div>
  <div id="box2">2</div>
  <div id="box3">3</div>
  <div id="box4">4</div>
  <div id="box5">5</div>
</div>
</div>

css样式

1,给元素设置显式的宽高,然后设置margin:auto,最简单易用,但是高度需要进行计算后设计,元素修改后页面布局直接失效。

div {
  border: 1px solid black;
}

#box {
width: 800px;
height: 400px;
}
#content {
   width: 300px;
  height: 200px;
   margin: 100px auto;
}

2,使用绝对定位+2D移动进行布局

#box {
width: 800px;
height: 400px;
position: relative;
}
#content {
position: absolute;
left: 50%;
top: 50%;
transform:translate(-50%, -50%);
width: 300px;
height: 200px;
}
3.flex布局,最为简单实用,可以对元素没多个元素进行水平垂直居中。
<div id="box">
  <div id="box1">1</div>
   <div id="box2">2</div>
  <div id="box3">3</div>
   <div id="box4">4</div>
  <div id="box5">5</div>
</div>
  div {
     border: 1px solid black;
  }
#box {
  width: 800px;
height: 400px;
display: flex;
justify-content:center;
align-items: center;
}
#box1 {
height: 234px;
width: 40px;
background-color: #acacac;
}
#box2 {
height: 200px;
width: 40px;
background-color: red;
}
#box3 {
height: 100px;
width: 30px;
background-color: #faaaaa;
}
#box4 {
height: 150px;FLEX
width: 230px;
background-color: #acedac;
}
#box5 {
height: 104px;
width: 202px;
background-color: rgb(76, 0, 255); flex
}
 
 

猜你喜欢

转载自www.cnblogs.com/qijilimeng/p/9327885.html