无论窗口大小如何,我都试图将 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%;
}
要了解有关 Flexbox 的更多信息,请访问:
- Using CSS flexible boxes 〜MDN
- A Complete Guide to Flexbox ~ CSS 技巧
请注意,所有主流浏览器都支持 Flexbox,except IE 8 & 9 。一些最新的浏览器版本,例如 Safari 8 和 IE10,需要 vendor prefixes 。要快速添加所需的所有前缀,请将 CSS 发布到此处的左侧面板中:Autoprefixer .
关于html - 保持所有图像居中并分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32788638/