How to vertically center align div having back ground image
This question already has an answer here:
Use this CSS. You'll have that Google logo centered vertically.
#imgDiv {
width: 300px;
height: 100px;
background-image: url("http://www.google.com/intl/en_com/images/srpr/logo3w.png");
background-repeat: no-repeat;
border: 1px solid blue;
position:relative;
top: 50%;
-moz-transform: translatey(-50%);
-ms-transform: translatey(-50%);
-o-transform: translatey(-50%);
-webkit-transform: translatey(-50%);
transform: translatey(-50%);
}
Easiest way would be to set the height of #imgDiv to height:100%; and then set the background-position to center, center.
#imgDiv {
width: 300px;
height: 100%;
background-image: url("http://www.google.com/intl/en_com/images/srpr/logo3w.png");
background-repeat: no-repeat;
border: 1px solid blue;
background-position:center,center;
}
Try like this: Demo
Updated demo as per your requirement: Note: If the text height increases, the background image will move upwards
div.outer {
display:table;
border: 1px solid red;
height:300px;
width:300px
}
.inner {
display:table-cell;
vertical-align:middle;
line-height:normal;
margin:0 auto;
text-align:center;
}
#imgDiv {
width: 300px;
height: 100px;
background-image: url("http://www.google.com/intl/en_com/images/srpr/logo3w.png");
background-position: center;
background-repeat: no-repeat;
border: 1px solid blue;
}
#spanid {
text-align: center;
}
HTML:
<div class="outer">
<div class="inner">
<div id="imgDiv"></div> <span id="spanid">Some text....</span>
</div>
</div>
链接地址: http://www.djcxy.com/p/41508.html
上一篇: 如何在div中垂直居中文本
下一篇: 如何垂直居中对齐具有背景图像的div