元素居中

水平居中

text-align

在父元素上设置text-align: center 使文字/图片水平居中。

.container {
  text-align: center;
}
margin
.container {
  width: 80%;
  margin:0 auto;
}

水平垂直居中

paddin + text-align:center;(子元素不是块级元素的情况下)

//HTML
<div class="ct">
    <p>这里是饥人谷</p>
    <p>这里是饥人谷</p>
  </div>

//CSS
.ct{
  padding: 40px 0;
  text-align: center;
  background:#ddd;
}

效果图:

padding+text-align:center

父元素不写高的情况下padding + margin(子元素是块级元素情况)

<div class="box">
    <div class="xx"></div>
</div>
.xx{
  width:100px;
  height:100px;
  background:#000;
  margin:0 auto;
}
.box{
  width:200px;
  background:#ccc;
  padding:20px 0;
}


position+margn:auto实现居中:

//HTML
<body>
 <div class="box">
  <div class="xx"></div>
 </div>
</body>
//CSS
  .box{
  width:200px;
  height:200px;
  background:#ccc;
  position:relative;
}
   .xx{
  width:100px;
  height:100px;
  background:#000;
  position:absolute;
  top:0;
  left:0;
  right:0;
  bottom:0;
  margin:auto;
}
position:absolute

position + transform:translate实现居中:

//HTML
<body>
  <div class="box">
    <div class="xx"></div>
 </div>
</body>
 //CSS
  .xx{
  width:100px;
  height:100px;
  background:#000;
  position:absolute;
  top:50%;
  left:50%;
  transform:translate(-50%,-50%)
}
.box{
  width:200px;
  height:200px;
  background:#ccc;
  position:relative;
}

效果图:

transform:translate

table-cell实现居中

//HTML
<body>
  <div class="box">
    <div class="xx"></div>
  </div>
</body>

//CSS
.box{
  width: 300px;
  height: 200px;
  border: 1px solid ;
  display: table-cell;
  vertical-align: middle;
}
.xx{
  width: 100px;
  border:1px solid;
  margin:0 atuo;
}

效果图

table-cell

display: flex

//HTML
<body>
  <div class="box">
    [图片上传失败...(image-cfdd76-1524486725573)]
  </div>
</body>

//CSS
.box{
  width: 300px;
  height: 200px;
  border: 1px solid ;
  display: flex;/* 弹性布局 */
  justify-content:center;/* 水平居中 */
  align-items:center;/* 垂直居中 */
}
.box img{
  width: 100px;
  border:1px solid;
}

效果图

display:flex
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容