如何实现居中

水平居中
1、内联元素居中:父元素设置text-align:center

 <div>hello world<div>

div{
  text-align:center;
}

2、块级元素居中:该元素设置margin-left:auto;margin-right:auto

 <div class="parent">
    <div class="child"></div>
  <div>
.parent{
  height:100px;
  background:red;
}
.child{
  height:50px;
  width:40px;
  background:green;
  margin-left:auto;
  margin-right:auto;
}

垂直居中
块级元素居中:
方法一:不设置.parent的height,设置.parent{padding:10px 0}

<div class="parent">
    <div class="child"></div>
<div>
.parent{
  padding:10px 0;
  background:red;
}
.child{
  height:50px;
  width:40px;
  background:green;
  margin-left:auto;
  margin-right:auto;
}

方法二:设置.parent的height,通过postion absoulte margin auto实现

 <div class="parent">
    <div class="child"></div>
  <div>
.parent{
  height:600px;
  background:red;
  position:relative;  
}
.child{
  background:green;
  position:absolute;
  width:300px;
  height:300px;
  top:0;
  left:0;
  right:0;
  bottom:0;
  margin:auto;
}

方法三:设置.parent的height,通过postion absolute margin 负值实现

  <div id="parent">
    <div id="child"></div>
  <div>
.parent{
  height:600px;
  background:red;
  position:relative;  
}
.child{
  background:green;
  position:absolute;
  width:300px;
  height:300px;
  top:50%;
  left:50%;
  margin-left:-150px;
  margin-top:-150px;
}

方法四:设置.parent的height,通过transform: translate(-50%,-50%);实现
translate(x,y) 括号的百分比数据,会以本身的长宽做参考,比如,本身的长为100px,高为100px. 那填(50%,50%)就是向右,向下移动50px,添加负号就是向着相反的方向移动

 <div class="parent">
    <div class="child">
    </div>
  <div>
.parent{
  height:600px;
  background:red;
  position:relative;  
}
.child{
  background:green;
  position:absolute;
  top:50%;
  left:50%;
  transform: translate(-50%,-50%);
}

方法五:通过flex实现

  <div class="parent">
    <div class="child"></div>
  <div>
.parent{
  background:red;
  height:600px;
  display: flex;
  justify-content: center;//justify-content属性定义了项目在主轴上的对齐方式。
  align-items: center; //align-items属性定义项目在交叉轴上如何对齐。
}
.child{
  background:green;
  width:300px;
  height:200px;
}

常用属性
transform
translate(x,y)
scale(x,y)
rotate(angle)

display:flex
justify-content:center//属性定义了项目在主轴上的对齐方式。
align-items:center//属性定义项目在交叉轴上如何对齐。

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

推荐阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 13,815评论 1 92
  • 收听音频,戳链接,旧号itclan已暂停使用,欢迎关注微信itclanCoder公众号可收听更多音频 前言 关于网...
    itclanCoder阅读 8,222评论 3 30
  • 原文地址:CSS各种居中实现方式 CSS居中是每次布局都需要面对的问题,但是同一个居中方法并不是任何元素都能使用的...
    薛普定朗谔克阅读 832评论 1 13
  • 单列布局水平居中水平居中 水平居中的页面布局中最为常见的一种布局形式,多出现于标题,以及内容区域的组织形式,下面介...
    Osmond_wang阅读 337评论 0 1
  • 植物园出来直奔狮峰龙井附近,买了一次茶,和茶农聊了一会儿,喝了几杯茶,知道了一些茶识。 龙井茶特点“色绿、香郁、味...
    oriyum阅读 439评论 0 1