不管窗口大小,我都试图将3个图像集中在窗口中间。当我调整窗口大小时,图像会相互折叠并被挤压。
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
width: 100%;
}
body {
display: table;
}
.my-block {
text-align: center;
display: table-cell;
vertical-align: middle;
}
</style>
<img src="http://www.clker.com/cliparts/d/X/i/j/F/U/expences-button-png-hi.png" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%) ; margin: 0px;" />
<div>
<img src="http://www.clker.com/cliparts/d/X/i/j/F/U/expences-button-png-hi.png" style="position: absolute; top: 55%; left: 50%; transform: translate(-50%, -50%);" />
<img src="http://www.clker.com/cliparts/d/X/i/j/F/U/expences-button-png-hi.png" style="position: absolute; top: 60%; left: 50%; transform: translate(-50%, -50%); " />
</div>
最佳答案
您可以在所有窗口大小中保持所有三个图像的垂直和水平居中,只需使用flexbox的几行代码。
HTML格式
<div id="container">
<img src="http://www.clker.com/cliparts/d/X/i/j/F/U/expences-button-png-hi.png">
<img src="http://www.clker.com/cliparts/d/X/i/j/F/U/expences-button-png-hi.png">
<img src="http://www.clker.com/cliparts/d/X/i/j/F/U/expences-button-png-hi.png">
</div>
CSS
html, body { height: 100%;}
#container {
display: flex;
flex-direction: column;
justify-content: center; /* center images vertically (in this case) */
align-items: center; /* center images horizontally (in this case) */
height: 100%;
}
DEMO
要了解有关flexbox的更多信息,请访问:
Using CSS flexible boxes~MDN
A Complete Guide to Flexbox~CSS技巧
请注意,所有主流浏览器都支持flexbox,except IE 8 & 9。一些最新的浏览器版本,如Safari8和IE10,需要vendor prefixes。要快速添加所需的所有前缀,请将CSS张贴在左侧面板中:Autoprefixer。