zoukankan      html  css  js  c++  java
  • 让块元素在div中水平居中,并且垂直居中的五种方法

    在写代码前,先做下准备工作,写两个div,设置下div的大小,把小的div放在大的div里面。可以给小的div设置下颜色,方便观看.

    方法一:写一个伪元素,将它设置为行内块元素,高度与父元素相同,写一条属性,vertical-align:middle,子元素也要写,具体代码如下:

    <style>
    div{width:500px;height:500px;box-shadow:0 0 5px #000; text-align:center;}
    .zi{width:100px;height:100px;background:#60C;display:inline-block;vertical-align:middle;}
    div:after{content:""; height:500px; background:#00C;display:inline-block;vertical-align:middle;}
    </style>
    </head>
    <body>
    <div >
        <div class="zi"></div>
    </div>

    方法二:利用定位,给大的div写一个position:relative;子元素写position:absolute; 这时子元素的包含块就是外面大的div,然后给里面的div写一下位置left:0;right:0;top:0;bottom:0;margin:auto;主要看一下CSS中的样式,具体代码如下:

    div{500px;height:500px;box-shadow:0 0 5px #000; position:relative;}
    .zi{100px;height:100px;background:#60C; position:absolute; left:0;right:0;top:0;bottom:0;margin:auto;}

    方法三:与方法二类似,也是用到定位,但是区别在于调整里面div位置时,不写right:0;bottom:0;而是使用margin可以设置负数,调整里面div的位置,具体代码如下:

    div{width:500px;height:500px;box-shadow:0 0 5px #000; position:relative;}
    .zi{width:100px;height:100px;background:#60C;position:absolute;left:50%;top:50%; margin:-50px 0 0 -50px;

    方法四:这种方法是在前一种方法上的延申,只是不是用margin,而是使用transform:translate()可以在不知道宽高的情况下进行居中,tranlate()函数是相对于自身的。

    具体代码如下:

    div{width:500px;height:500px;box-shadow:0 0 5px #000;position:relative;}
    .zi{width:100px;height:100px;background:#60C;position:absolute;left:50%;top:50%;transform:translate(-50px,-50px);}

    方法五:使用弹性盒,给父元素设置这三条属性display:flex;  水平方向居中 justify-content:center;垂直方向居中align-items:center;具体代码如下:

    div{width:500px;height:500px;box-shadow:0 0 5px #000; display:flex; justify-content:center;align-items:center;}
    .zi{width:100px;height:100px;background:#60C;}
  • 相关阅读:
    emacs jedi
    opencv 基本demo
    emacs列编辑
    observable operator example
    angular keydown 例子
    回调和匿名函数
    gin cors
    angular rxjs
    python dbus note
    视频截图
  • 原文地址:https://www.cnblogs.com/paixiaoxin/p/11918054.html
Copyright © 2011-2022 走看看