怎么让div里的div垂直居中(一个div在另一个div内水平垂直两方向居中的方法总结)
小编在做练习时遇到了一个问题:如何使一个div在另一个div里面水平和垂直两个方向全部居中。之前一般的情况都是一个div在另一个div里面水平居中,直接使用margin:0 auto;即可解决。这次的情况第一次遇到,网上找了一些方法,亲测有效,总结如下,将其放入一个页面内了。
HTML部分:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div class="parent1">
<div class="child1">方法一</div>
</div>
<div class="parent2">
<div class="child2">方法二</div>
</div>
<div class="parent3">
<div class="child3">方法三</div>
</div>
<div class="parent4">
<div class="child4">方法四</div>
</div>
</body>
</html>
<style>
*{margin: 0;padding: 0;}
/*方法一*/
.parent1{
width: 500px;height: 200px;
border: 4px solid #FF4500;
position: relative;
margin-top: 20px;margin-bottom: 20px;
}
.child1{
width: 200px;height: 150px;
margin: auto;position: absolute;
top: 0;right: 0;bottom: 0;left: 0;
background-color: #008B8B;
line-height: 150px;
text-align: center;
color: white;
}
/*方法二*/
.parent2{
width: 500px;height: 200px;
border: 4px solid #008B8B;
display: table-cell;
vertical-align: middle;
text-align: center;}
.child2{
width: 200px;height: 150px;
display: inline-block;
background-color: #008B8B;
line-height: 150px;color: white;
}
/*方法三*/
.parent3{
width: 500px;height: 200px;
border: 4px solid #008B8B;
margin-top: 20px;
display: flex;
justify-content: center;
align-items: center;
}
.child3{
width: 200px;height: 150px;
background-color: #008B8B;
line-height: 150px;
text-align: center;
color: white;
}
/*方法四 */
.parent4{
width: 500px;height: 200px;
border: 4px solid #FF4500;
position: relative;
margin-top: 20px;
}
.child4{
width: 200px;height: 150px;
background-color: #008B8B;
position: absolute;
top: 50%;left: 50%;
margin-left: -100px;
margin-top: -75px;
line-height: 150px;
text-align: center;
color: white;
}
</style>
最后效果图如下:
以上就是几种简单的居中方法,本文纯属练习,如有错误欢迎各位指出。
,免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com