美文网首页
css/css3实现水平垂直居中

css/css3实现水平垂直居中

作者: 张鸽 | 来源:发表于2018-03-17 13:53 被阅读0次

水平居中:

  • 行内元素
    只需要把行内元素包裹在一个属性display为block的父层元素中,并且把父层元素添加属性text-align:center;
  • 块级元素
    设置width值并添加属性margin:0 auto;
    • 多个块级元素
      将元素的display属性设置为inline-block,并且把父元素的text-align属性设置为center
    • 多个块级元素(flex布局)
      给父级元素添加属性:display:flex;和justify-content:center;

垂直居中:

  • 行内元素(单行)
    将元素的父元素height和line-height设置成一样大小即可实现垂直居中
  • 行内元素(多行)
    在父元素中设置display:table-cell;vertical-align:middle;
  • 块级元素(已知高度)id值为”div“
#div{
    top: 50%;
    margin-top: -50px;  /* margin-top值为自身高度的一半 */
    position: absolute;
    padding:0;
}

水平垂直居中

  • 已知宽高 方案1
<div id="div1">
    <p>水平垂直居中</p>
</div>
<style>
        #div1{
            width:200px;
            height: 200px;
            position: absolute;
            left:50%;
            top:50%;
            margin-top: -100px;
            margin-left: -100px;
            background-color: antiquewhite;
            text-align: center;
        }
</style>
  • 已知宽高 方案2
<div id="div1">
    <p>水平垂直居中</p>
</div>
 <style>
        #div1{
            width:200px;
            height: 200px;
            position: absolute;
            margin: auto;
            left:0;
            right:0;
            top:0;
            bottom:0;
            text-align: center;
            background-color: antiquewhite;
        }
    </style>
  • 未知宽高(css3的transform)
<div id="div1">
    <p>水平垂直居中</p>
</div>
    <style>
        #div1{
            position: absolute;
            left: 50%;
            top:50%;
            transform: translate(-50%,-50%);//使用css3的transform属性
        }
    </style>
  • 未知宽高(flex布局)
<div id="div1">
    <p>水平垂直居中</p>
</div>
<style>
        #div1{
            display: flex;                //使用flex布局
            justify-content: center;      //子元素水平居中
            align-items: center;          //子元素垂直居中
            height: 400px;                //设置高度来查看垂直居中效果
            background-color: antiquewhite;
            }
</style>

git地址:https://github.com/zhangge1998/-centering-control

相关文章

网友评论

      本文标题:css/css3实现水平垂直居中

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