css 布局(垂直居中,水平居中)

实现垂直居中布局

1.已知宽高

/* 1 */
.container{
  width: 300px;
  height: 300px;
  background: yellowgreen;
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -150px;
  margin-top: -150px;
}
/* 2 */
.container{
  width: 300px;
  height: 300px;
  background: yellowgreen;
  position: absolute;
  top: calc(50% - 150px);
  left: calc(50% - 150px);
}

2.未知宽高

/* 1 */
.container{
  background: yellowgreen;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
/* 2 position + auto*/
.container{
  background: yellowgreen;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}
/* 3 flex+ auto */
.wrapper {
  width: 100%;
  height: 100vh;
  display: flex;
}
.wrapper .content {
  margin: auto;
}
/* 4. 父元素居中*/
.wrapper {
   display: flex;
   /* 盒子横轴的对齐方式 */
   justify-content: center;
   /* 盒子纵轴的对齐方式 */
   align-items: center;
}
/* 5.body内部居中*/
.content {
   /* 1vh = 1% * 视口高度 */
   margin: 50vh auto;
   transform: translateY(-50%);
}

css 盒子模型(默认为content-box)

CSS盒模型本质上是一个盒子,封装周围的HTML元素,它包括:边距,边框,填充,和实际内容。


image.png
  • 标准盒子模型:width = content
  • IE盒子模型:width = content + pading + border

  • 设置标准盒子模型:box-sizing : content-box
  • 设置IE盒子模型:box-sizing : border-box
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容