已知/未知寬高的浮動元素水平垂直居中對齊
阿新 • • 發佈:2018-12-31
一、已知寬高的浮動元素水平垂直居中對齊
效果:
樣式CSS:
<style>
.parent{
position:relative;
border:2px solid #0f0;
}
.child{
float:left;
background-color:#6699ff;
width:200px;
height:200px;
border:2px solid #f00;
position:absolute;
top:50%;
left:50%;
margin-top:-100px;
margin-left:-100px;
}
</style>
模板HTML:
<body>
<div class="parent">
<div class="child"></div>
</div>
</body>
二、未知寬高的浮動元素水平垂直居中對齊
效果:
樣式CSS:
<style>
.parent{
position:relative;
border:2px solid #0f0;
}
.child{
float:left;
background-color:#6699ff;
width:260px;//元素寬高隨便設定
height:260px;
border:2px solid #f00;
margin:auto;
position:absolute;
top:0;
left:0;
bottom:0;
right:0;
}
</style>
模板HTML:
<body>
<div class="parent">
<div class="child"></div>
</div>
</body>
三、圖片的水平垂直居中
效果:
樣式CSS:
<style>
.container{
display:table-cell;
text-align:center;
vertical-align:middle;
width:500px;
height:300px;
border:2px solid #f00;
}
img{
width:200px;
height:200px;
border:2px solid #0f0;
}
</style>
模板HTML:
<div class="container">
<img src="watermelon.jpg" alt="">
</div>