css实现内容水平垂直居中

首先,我们先写一个网页,搭一个基础的布局:
头部高度100px,左侧宽度100px,白色部分为内容区域,宽高不定,随着浏览器大小自适应,现在我们想办法让
这是一个儿子 居中显示
在这里插入图片描述
基础布局的代码如下所示:

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

<head>
  <meta charset="UTF-8">
  <title>元素居中</title>
  <style type="text/css">
    * {
      padding: 0;
      margin: 0;
    }

    html,
    body {
      height: 100%;
    }

    .bigBox {
      width: 100%;
      height: 100%;
    }

    .header {
      width: 100%;
      height: 100px;
      background: green;
    }

    .container {
      display: flex;
      height: calc(100% - 100px);
    }

    .left {
      height: 100%;
      width: 100px;
      background: yellow;
      float: left;
    }
  </style>
</head>

<body>
  <div class="bigBox">
    <!-- 头部 -->
    <div class="header"></div>
    <!-- 头部以下区域 -->
    <div class="container">
      <!-- 左侧 -->
      <div class="left"></div>
      <!-- 内容区域 -->
      <div class="father">
        <div class="child">
          这是一个儿子
        </div>
      </div>
    </div>
  </div>
</body>
<script>

</script>

</html>

1. 父元素宽高不定

1.1 使用calc计算出父元素的宽,使用display给子元素定位;或者使用flex: 1代替宽高计算

.father {
      background: pink;
      float: left;
      display: flex;
      /* 垂直居中 */
      align-items: center;
      /* 横向居中 */
      justify-content: center;
      
      /* 方法一:使用flex: 1 */
      /* flex: 1; */

      /* 方法二:计算宽高 */
      width: calc(100% - 100px);
      height: 100%;
    }

.child {
	  background-color: red;
	}

1.2 使用calc计算出父元素的宽,子元素绝对定位,并使用transform计算子元素移动位置;或者使用flex: 1代替宽高计算

transform的translate() 方法是从当前位置移动元素(根据为 X 轴和 Y 轴指定的参数)
transform:translate(-50%, -50%)
(负数向左移动,负数向上移动)
在style里面加上如下代码:

.father {
      background: pink;
      float: left;
      position: relative;

      /* 方法一:使用flex: 1 */
      /* flex: 1; */

      /* 方法二:计算宽高 */
      width: calc(100% - 100px);
      height: 100%;
    }

.child {
	   background-color: red;
	   position: absolute;
	   left: 50%;
	   top: 50%;
	   transform: translate(-50%, -50%);
	 }

效果如图所示:
在这里插入图片描述

2. 父元素宽高固定

.father {
      background: pink;
      float: left;
      width:600px;
      height: 400px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
.child {
     background-color: red;
    }

或者

.father {
      background: pink;
      float: left;
      position: relative;
      width:600px;
      height: 400px;
    }

.child {
	  background-color: red;
	  position: absolute;
	  left: 50%;
	  top: 50%;
	  transform: translate(-50%, -50%);
	}

效果如图:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值