实现居中

实现居中

line-hight实现垂直居中
  • 将line-hight与容器高设置一致。demo
通过display:flex
  • 通过设置justify-content和align-items实现居中。 demo
.fatherclass {
  display: flex;
  justify-content: center;
  align-items: center;
}
定位与translate()实现居中
  • 实现垂直居中 demo
.class {
  position: relative;
  top: 50%;
  transform: translate(0,-50%);
}
  • 可使块级元素在父容器中水平垂直居中 demo
.class {
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}
  • 使用绝对定位在浏览器窗口中水平垂直居中 demo
.class {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}
display: table-cell实现居中

这将使元素不再是block元素,宽度不再自适应。

  • 使元素在父容器中水平垂直居中 demo
.fatherclass {
  display:table-cell;
  text-align: center;
  vertical-align: middle;
}
vertical-align与display: inline-block实现居中

注意vertical-align是调整不了块级元素。

  • 使添加一个伪元素,使inline-block属性元素在父容器中水平垂直居中 demo
.fatherclass:before{
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}

.class {
  display: inline-block;
  vertical-align: middle;
  border: 1px dashed;
}

布局

  • 两栏布局
    一个float元素加上一个block元素,使用margin把block元素的距离与float元素拉开即可。demo
  • 三栏布局
    两个个float元素加上一个block元素,使用margin把block元素的距离与float元素拉开即可。demo
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。