zoukankan      html  css  js  c++  java
  • 利用css来让一个div在页面中垂直居中的方法

    一、如何让一个div在页面中垂直居中(请至少列出三种)

    1.距离页面窗口左边框和上边框的距离设置为50%,这个50%就是指页面窗口的宽度和高度的50%,最后将该DIV分别左移和上移,左移和上移的大小就是该DIV宽度和高度的一半。

    300px; 

     height:200px; 

     position:absolute;

     left:50%

     top:50%;  

     margin:-100px 0 0 -150px ;

    2.使用jquery代码

     $(window).resize(function(){ 

       $(".mydiv").css({ 

         position: "absolute", 

         left: ($(window).width() - $(".div").outerWidth())/2, 

         top: ($(window).height() - $(".div").outerHeight())/2 

       });        

    }); 

    3.使用绝对定位;top,bottom,left,right分别都为零

    父元素设置为:

      800px;

               height:500px;

               border:2px solid #000;

               position:relative;

    子元素设置为:

      200px;

                height:200px;

                margin: auto;

                position: absolute;

                top: 0; left: 0; bottom: 0; right: 0;

                

    4.(此方法在IE中可以实现只元素在父级元素中垂直居中,但在chrome中还没有实现水平居中),使用display:table-cell

    父元素设置为:

    800px;

    height:500px;

    border:2px solid #000;

    display:table-cell;

    vertical-align:middle;

    text-align: center;

    子元素设置为:

    200px;

    height:200px;

    display:inline-block;

    5.使用弹性布局的方式来解决

    父级元素设置为

    800px;

    height:500px;

    border:2px solid #000;

    display:flex;

    justify-content:center;

    align-items:center;

    子元素设置为:

     200px;

    height: 200px;

    background-color: red;

    6.绝对定位和transfrom

    style>
        *{
            padding: 0;
            margin: 0;
        }
        .box{
             300px;
            height: 300px;
            background:#e9dfc7; 
            border:1px solid red;
            position: relative;
    
        }
        img{
             100px;
            height: 100px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%,-50%);
        }
    </style>
    <!--html -->
    <body>
        <div class="box" >
            ![](3.jpg)
        </div>
    </body>
  • 相关阅读:
    java基础---多线程---volatile详解
    java基础---多线程---线程的几种状态及其转换,wait,notify,sleep,yield,join
    java基础---设计一个死锁
    count(1) and count(*),count(字段)区别及效率比较
    mysql之字段约束-第五篇
    mysql之数据表基本操作-第四篇
    mysql之数据类型-第三篇
    mysql之存储引擎-第二篇
    mysql之数据库操作-第一篇
    Redis详解
  • 原文地址:https://www.cnblogs.com/fireporsche/p/6290637.html
Copyright © 2011-2022 走看看