zl程序教程

您现在的位置是:首页 >  其他

当前栏目

无固定高度的div垂直居中

2023-04-18 14:48:06 时间

1、无固定高度的div垂直居中 – CSS

实现效果图如下:

代码附上:

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width,user-scalable=0">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="black">
    </head>

    <body>
        <!--一个未知宽高的弹出框,水平垂直居中-->
        <div style="position:relative;width:100%;height:450px;border:1px solid #888">方法1
            <div class="modal">
                <div class="modal-header">弹出窗标题</div>
                <div class="modal-body">
                    .modal类中的position: absolute;表示现对于父类元素height:450px;来居中的
                    .modal类中的position: fixed;表示现对于body来居中的
                </div>
            </div>
        </div>

        <style type="text/css">
            .modal-header {
                padding: 10px 20px;
                text-align: center;
                background: rgba(0, 0, 0, .25);
                color: #fff;
            }

            .modal-body {
                padding: 20px;
                background: #fff;
            }

            .modal {
                overflow-y: auto;
                max-height: 95%;
                font-size: 16px;
                z-index: 103;
                border-radius: 5px;
                background: #ffffff;
                width: 80%;
                border: 1px solid #e5e5e5;
                color: #333;
                display: block;
                box-shadow: 0 0 3px rgba(0, 0, 0, .1);
                /**主要代码*/
                position: absolute;
                top: 50%;
                left: 50%;
                -webkit-transform: translate(-50%, -50%);
                transform: translate(-50%, -50%);
            }
        </style>
        <!--end-->
    </body>

</html>

2、CSS3垂直居中

section {
    display: flex;
    display: -webkit-flex;
    display: -webkit-box;
}

section div {
    border: 1px solid #dddddd;
    height: 200px;
    margin-right: 20px;
    width: 200px;
    border-radius: 5px;
    cursor: pointer;
    box-shadow: 5px 4px 13px -1px #8e8e8e;
    text-align: center;

    display: flex;
    justify-content: center;
    align-items: center;

}

<section>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
</section>