美文网首页
如何实现居中

如何实现居中

作者: 爱笑的疯小妞 | 来源:发表于2018-03-18 12:16 被阅读0次

    水平居中
    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//属性定义项目在交叉轴上如何对齐。

    相关文章

      网友评论

          本文标题:如何实现居中

          本文链接:https://www.haomeiwen.com/subject/uateqftx.html