不同场景下的垂直水平居中

场景一:物体A相对于整个屏幕水平垂直居中(弹出框)

注:黑色边框是屏幕的尺寸

方法一: 将外边距设置为容器自身宽高的一半

top 和 left 均设置为 50%,然后设置容器外边距 margin 的负间距

(即:margin-top 为容器自身高度一半的负值,margin-left 为容器自身宽度一半的负值)

<body>	
  <div class="content">
  </div>
</body>
 
<style>	
  .content {
    position: absolute;
    width: 500px;
    height: 200px;    
    left: 50%;
    top: 50%;
    margin: -100px 0 0 -250px;     /* 将外边距设置为容器自身的一半 */
    background-color: red;
  }
</style>

方法二:使用  `transform` 属性

top 和 left 均设置为 50%,然后使用  `transform`  属性

<body>
  <div class="content"></div>
</body>
 
<style>
  .content{
    position: absolute;
    width: 500px;
    height: 200px;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);    /* 使用 `transform`属性 */
    background-color: pink;
  }
</style>

方法三:设置外边距为 auto

top 、left 、bottom 、right 均设置为 0 ,然后设置外边距 margin 为 auto

<body>
  <div class="content"></div>
</body>
 
<style>
  .content{
    position: absolute;
    width: 200px;
    height: 100px;    
    top: 0;  
    left: 0;
    bottom: 0;
    right: 0;
    margin: auto;       /* 设置外边距为 auto */
    background-color: blue;	
  }
</style>

场景二:物体 B 相对于物体 A 水平垂直居中(大div套小div)

注:黑色框表示屏幕,B是相对于A垂直居中

方法一:使用 flex 布局

将 display 值设为 flex,垂直居中 align-items: center;    水平居中 justify-content: center;

<body>
  <div class="container">
    <div></div>   
  </div>
</body>

<style>
  .container {
    width: 300px;
    height: 300px;
    background-color: red;
    display: flex;    /* display 值为 flex */
    align-items: center;        /* 垂直居中 */
    justify-content: center;    /* 水平居中 */
  }
  .container div {
    width: 100px;
    height: 100px;
    background-color: green;		
  }  
</style>

方法二:给父元素 div 添加宽高,然后设置父元素的 position 为 relative;子元素参考场景一的三种写法

以【场景一】中的【方法一】为例:

<body>
  <div class="container">	
    <div class="content">
    </div>
  </div>
</body>

<style>	
  .container{
    width:600px;
    height:600px;
    position: relative;    /* 将父元素 position 设置为 relative */  
    background: yellow;
  }
  .container .content {
    position: absolute;
    width: 500px;
    height: 200px;    
    left: 50%;
    top: 50%;
    margin: -100px 0 0 -250px;     /* 将子元素外边距设置为容器自身的一半 */
    background-color: red;
  }
</style>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Windyluna

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值