css垂直居中的几种方法
- 这个是先把父级元素的position设置为relative;然后子元素设置为position:absolute;
然后设置子元素:top:50%;transform:translateY(-50%),记住,这样做的前提是父元素和子元素都有实际的高度。
这样也可以:top:50%; margin-top:-50px;
两种方法的原理其实是一样的,都是先把子元素下移50%父元素的高度,然后再上移自身高度的50%;注意,用margin-top时,要用实际高度,不能用百分数表示。
<style>
- .parent {
- width:200px;
- height:200px;
- background-color:#ccc;
- position:relative;
- }
- .child {
- width:100px;
- height:100px;
- background:#e4393c;
- position:absolute;
- top:50%;
- transform:translateY(-50%);
//margin-top:(-50px)(这样也可以)
- }
- </style>
- </head>
<body>
<div class="parent">
<div class = "child"></div>
</div>
</body>2.这种方法用的是flex布局,先把父级display:flex;
然后设置align-items:center(这是设置父元素里的元素垂直居中),justify-content:center(设置父元素里的子元素水平居中);
代码如下:
<style>
.parent {
width:200px;
height:200px;
background-color:#ccc;
display:flex;
align-items:center;
justify-content:center;
}
.child {
width:100px;
height:100px;
background:#e4393c;
position:absolute;
}
</style>
</head>
<body>
<div class="parent">
<div class = "child"></div>
</div>
</body><br /><span> 3.这个方法直接上代码,父元素设置position:relative;子元素设置positio:absolute,然后设置子元素top:0;bottom:0;margin-top:auto; 值得注意的是,<br />top和bottom值要设置相等就可以,不一定为0;
<style>
#box {
width: 300px;
height: 300px;
background: #ddd;
position: relative;
}
#child {
width: 200px;
height: 100px;
background: #A1CCFE;
position: absolute;
top:;
bottom:;
margin: auto;
line-height: 100px;
}
</style>
</head>
<body>
<div id="box">
<div id="child">呆呆今天退役了(。﹏。)</div>
</div>
</body><span>
4.还有一种方法也可以,其实也是flex 的一种,主要设置宽高,然后设置父元素:display:flex; flex-direction:column;justify-content:center;
相关推荐
jiedinghui 2019-12-23
hellowzm 2020-10-12
qiupu 2019-06-28
gufudhn 2020-06-12
沈宫新 2020-05-04
/*垂直居中,div上边界距离窗口上边的距离为窗口高度的50%,并针对不同浏览器进行兼容。-- 在外层添加一个div,把行内容居中,添加.row .justify-content-center -->
Phoebe的学习天地 2020-04-14
STPace 2020-02-17
xiaohuli 2020-02-12
liusure0 2020-01-11
wangjie 2020-01-12
zuncle 2019-12-30
libowen0 2014-05-30
Simagle 2015-05-27
cssuperman 2018-04-01
ThikHome 2019-07-01
Phoebe的学习天地 2019-07-01
Phoebe的学习天地 2019-07-01