zoukankan      html  css  js  c++  java
  • css实现子层在父层中水平垂直居中

    例子:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>css实现子层在父层中水平垂直居中</title>
    <style type="text/css">
    #parent {
        position:absolute;
        top:50%;
        left:50%;
        margin:-250px 0 0 -200px;
        height:500px;
        width:400px;
        background-color:red;
    }
    #child {
        position:absolute;
        top:50%;
        left:50%;
        margin:-100px 0 0 -150px;
        height:200px;
        width:300px;
        background-color:green;
    }
    </style>
    </head>
    <body>
    <div id="parent">
        <div id="child"></div>
    </div>
    </body>
    </html>

    解释:
        id为parent的层的父层是body,id为child的层的父层是parent。
    需要注意点:
        一:子层必须设置position为absolute,父层必须设置position为relative;absolute可以作为另一个absolute的父层。
        二:子层top设置为50%,left也设置为50%。
        三:子层的margin-top设置为本身高度的一半,并且为负值;margin-left设置为本身宽度的一半,并且为负值。
    效果:
        子层水平垂直居中于父层。

  • 相关阅读:
    【题解】LOJ #6488 数表【FWT】
    【题解】[Comet OJ Contest #11 F] arewell【子集卷积】
    【CF757F】 Team Rocket Rises Again 【支配树】
    支配树学习笔记
    JS模拟实现题目(new debounce throwee 等)
    React生命周期
    js转义符
    CSS3中的transform转换属性
    animation动画
    flex
  • 原文地址:https://www.cnblogs.com/kelly007/p/5072144.html
Copyright © 2011-2022 走看看