【CSS 布局】水平垂直方向居中

【CSS 布局】水平垂直方向居中

单行元素

<div class="container">
    <div class="item">div>
div>
  • 方式一:relativeabsolute
.container {
  position: relative;
  height: 400px;
  border: 1px solid #ccc;
  .item {
    position: absolute;
    width: 200px;
    height: 200px;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    margin: auto;
    border: 1px solid #ccc;
  }
}
  • 方式二:relativeabsolute(变种,适合于宽高固定)
.container {
  position: relative;
  height: 400px;
  border: 1px solid #ccc;
  .item {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -100px;
    margin-bottom: -100px;
    width: 200px;
    height: 200px;
    border: 1px solid #ccc;
  }
}
  • 方式三:flexmargin
.container {
  display: flex;
  height: 400px;
  border: 1px solid #ccc;
  .item {
    width: 300px;
    height: 300px;
    border: 1px solid #ccc;
    margin: auto; /* 关键点 */ 
  }
}
  • 方式四:flex
.container {
  display: flex;
  height: 400px;
  border: 1px solid #ccc;
  justify-content: center;
  align-items: center;
  .item {
    width: 300px;
    height: 300px;
    border: 1px solid #ccc;
  }
}
  • 方式五:flex
.container {
  display: flex;
  height: 400px;
  border: 1px solid #ccc;
  justify-content: center;
  .item {
    width: 300px;
    height: 300px;
    border: 1px solid #ccc;
    align-self: center;
  }
}

多行元素

<div class="container">
    <img src="./login.png" alt="" />
    <p>欢迎访问我的个人博客 hhmax.xyzp>
    <button>按钮button>
div>
.container {
  height: 400px;
  border: 1px solid #ccc;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
}

你可能感兴趣的:(css笔记,css,前端)