[英]Center div vertically and horizontally inside another div
如果调整结果窗格的大小以使其更窄,您将看到图像区域将相应地调整大小。
我希望在发生这种调整大小时,使文本始终垂直和水平居中。
我无法为此找到合适的CSS。
.holders { position: absolute; bottom: 0; left: 50%; margin-left: -150px; /*half of image width*/ } .holder { float: left; /*this cannot be changed because we have a row of blocks like the example one in the bottom*/ position: relative; } .text { position: absolute; top: 150px; /*this is not right at this moment*/ } .img { width: 100%; height: auto; }
<div style="position: fixed;top:0;left:0;width:100%;height:100%"> <div class="holders"> <div class="holder"> <div class="text"> This is text that should be in the center of the block vertically and horizontally </div> <img class="img" src="http://www.fnordware.com/superpng/pnggrad8rgb.png" /> </div> </div> </div>
这是jsfiddle示例: https ://jsfiddle.net/mddc/4tx5h1tq/34/
谢谢你的帮助!
.holders { position: absolute; bottom: 0; left: 50%; /* margin-left: -150px; */ transform: translateX(-50%); /* see comments below */ } .holder { float: left; position: relative; } .text { width: 100%; text-align: center; position: absolute; top: 50%; /* center text vertically */ left: 50%; /* center text horizontally */ transform: translate(-50%, -50%); /* horizontal & vertical centering fine-tuning; http://stackoverflow.com/a/36817384/3597276 */ } .img { width: 100%; height: auto; }
<div style="position: fixed;top:0;left:0;width:100%;height:100%"> <div class="holders"> <div class="holder"> <div class="text"> This is text that should be in the center of the block vertically and horizontally </div> <img class="img" src="http://www.fnordware.com/superpng/pnggrad8rgb.png" /> </div> </div> </div>
您是否考虑过使用flexbox ? 只需很少的更改,它就能完全按照您的要求进行操作。
.holders {
position: absolute;
bottom: 0;
left: 50%;
margin-left: -150px; /*half of image width*/
}
.holder {
float: left; /*this cannot be changed because we have a row of blocks like the example one in the bottom*/
position: relative;
}
.text {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
display: flex;
flex-direction: column;
justify-content: space-around;
}
.text p {
flex: 0 0 auto;
margin: 0;
text-align: center;
}
.img {
width: 100%;
height: auto;
}
您可以用更少的代码来做同样的事情。
的HTML
<div class="center">
<p class="text">This is text that should be in the center of the block vertically and horizontally</p>
</div>
的CSS
.center {
-webkit-align-items: center;
-webkit-justify-content: center;
align-items: center;
background: url('http://www.fnordware.com/superpng/pnggrad8rgb.png');
display: -webkit-flex;
display: flex;
height: 300px;
justify-content: center;
width: 300px;
}
链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.