子元素在父元素中垂直居中

方法一:

  要求水平和垂直居中,可以是用margin:0 auto;和marggin-top:(父元素-子元素)/2

方法二:

       要求子元素垂直居中,水平更加设计布局,可以使用定位,父元素relative,子元素absolute,并且子元素top设置50%,margin-top设置为子元素高的一半的负值

!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>让DIV标签中的P标签水平和垂直都居中</title>
    <style type="text/css">
        div {
            position: relative;
            width:400px;
            height:300px;
            overflow:hidden;
            background-color: #0cbb08;
        }
        p {
            position: absolute;
            top: 50%;
            margin-top: -25px;
            border:1px solid #333;
            width:200px;
            height: 50px;
            border-radius: 25px;
            background-color: #ff9236;
            line-height: 50px;
            text-align: center;
        }
        * { margin:0; padding:0;}
    </style>
</head>
<body>

<div>
    <p>我要水平和垂直都居中</p>
</div>

</body>
</html>

  

猜你喜欢

转载自www.cnblogs.com/gopark/p/9172995.html