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

方法一:

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

方法二:

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
!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>

  

 

posted @   极客小乌龟  阅读(564)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示