css垂直水平居中

css 元素居中

CSS 布局,推介统统使用 Flex

<style>
  .father {
    background-color: pink;
  }
  .child-1 {
    background-color: #ccc;
  }
  .child-2 {
    background-color: orangered;
  }
</style>

<body>
  <div class="father">
    <span class="child-1">hellow world</span>
    <div class="child-2">Japan</div>
  </div>
</body>

水平居中

水平居中,Dom 节点至少需要有一个包含关系,也就是两个元素

  • 1.让子元素水平居中,子元素如果为行内元素,那么
.father {
  text-align: center;
}
  • 2.让子元素水平居中,子元素如果为块元素,前提是子元素必须要有一个宽度,那么
.child-2 {
  background-color: orangered;
  width: 200px;
}
  • 3.让子元素作为整体水平居中,那么(推介)
.father {
  display: flex;
  justify-content: center;
}
  • 4.使用 CSS3 中新增的 transform 属性,那么
.father {
  position: relative;
}
.child-1 {
  position: absolute;
  left: 50%;
  transform: translate(-50%, 0);
}
  • 5.使用绝对定位方式, 以及负值的 margin-left,前提是子元素宽度一定,那么
.child-1 {
  position: absolute;
  width: 200px;
  left: 50%;
  margin-left: -100px;
}

垂直居中

  • 1.若子元素是单行文本, 则可设置子元素 line-height 等于父元素高度,前提是父元素有确切高度,不能是百分比
.father {
  height: 200px;
  background-color: pink;
}

.child-1 {
  background-color: #ccc;
  line-height: 200px;
}
  • 2.若子元素是行内块级元素, 基本思想是使用 display: inline-block, vertical-align: middle 和一个伪元素让内容块处于容器中央.(兼容 IE7)
.father {
  height: 300px;
  background-color: pink;
}

.father::after {
  display: inline-block;
  vertical-align: middle;
  content: "";
  height: 100%;
}
.child-2 {
  background-color: orangered;
  display: inline-block;
  vertical-align: middle;
}

元素高度不定

  • 3.使用 flex,需浏览器厂商前缀
.father {
  background-color: pink;
  width: 300px;
  height: 300px;
  display: flex;
  align-items: center;
}
  • 4.使用 vertical-align 属性,需浏览器厂商前缀
.father {
  background-color: pink;

  width: 300px;
  height: 300px;
  display: table;
}

.child-1 {
  background-color: #ccc;

  display: table-cell;
  vertical-align: middle;
}

.child-2 {
  background-color: orangered;

  display: table-cell;
  vertical-align: middle;
}
  • 5.使用 transform,需浏览器厂商前缀
.father {
  position: relative;
}
.child-1 {
  position: absolute;
  top: 50%;
  -webkit-transform: translate(0, -50%);
  -ms-transform: translate(0, -50%);
  transform: translate(0, -50%);
}
  • 6.使用绝对定位方式, 以及负值的 margin-left,前提是子元素高度一定,父元素有高度,那么
.father {
  background-color: pink;
  height: 300px;
  position: relative;
}
.child-2 {
  position: absolute;
  height: 100px;
  top: 50%;
  margin-top: -50px;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值