水平居中和垂直居中

水平居中方法1(margin:0 auto):

<div style="width: 300px ; height:300px; background-color: red ;">
    <div style="width: 100px;height:100px;background-color: yellow ; margin: 0 auto"></div>
</div>

垂直居中方法1(table-cell + vertical-align:middle):

<div style="width: 300px ; height:300px; background-color: red ;display:table-cell;vertical-align: middle">
    <div style="width: 100px;height:100px;background-color: yellow ;"> </div>
</div>

水平居中方法2(绝对定位):

<div style="width: 300px ; height:300px; background-color: red; position: relative">
    <div style="width: 100px;height:100px;background-color: yellow ;position: absolute; left:50%;margin-left: -50px"> </div>
</div>

同理对应垂直居中方法2:

<div style="width: 300px ; height:300px; background-color: red; position: relative">
    <div style="width: 100px;height:100px;background-color: yellow ;position: absolute; top:50%;margin-top: -50px"> </div>
</div>

水平居中方法3(子div浮动+相对定位):

<div style="width: 300px ; height:300px; background-color: red ;">
    <div style="float:left;margin-left:50%; position:relative; left:-50px;width: 100px;height:100px;background-color: yellow ; "> </div>
</div>

同理对应垂直居中方法3:

<div style="width: 300px ; height:300px; background-color: red ;">
    <div style="float:left;margin-top:50%; position:relative; top:-50px;width: 100px;height:100px;background-color: yellow ; "> </div>
</div>

水平居中方法4(flex):

<div style="display:flex; justify-content:center ;width: 300px ; height:300px; background-color: red ;">
    <div style="width: 100px;height:100px;background-color: yellow ; "> </div>
</div>

同理垂直居中方法4:

<div style="display:flex; align-items:center;width: 300px ; height:300px; background-color: red ;">
    <div style="width: 100px;height:100px;background-color: yellow ; "> </div>
</div>

水平居中效果图:

居中布局

垂直居中效果图:

居中布局

相关文章:

  • 2022-01-02
  • 2022-02-18
  • 2022-12-23
  • 2022-12-23
  • 2021-09-17
  • 2019-08-23
  • 2019-09-29
  • 2021-10-04
猜你喜欢
  • 2021-07-03
  • 2021-04-25
  • 2021-10-16
  • 2021-12-02
  • 2021-05-21
相关资源
相似解决方案