html - 保持所有图像居中并分开

标签 html css flexbox

无论窗口大小如何,我都试图将 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 的更多信息,请访问:


请注意,所有主流浏览器都支持 Flexbox,except IE 8 & 9 。一些最新的浏览器版本,例如 Safari 8 和 IE10,需要 vendor prefixes 。要快速添加所需的所有前缀,请将 CSS 发布到此处的左侧面板中:Autoprefixer .

关于html - 保持所有图像居中并分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32788638/

相关文章:

php - 获取dropdown的值并在php中使用

javascript - 使用 JQuery 单击下拉菜单向下滑动

javascript - 将 Div 容器与 Display Flex 的底部对齐

python - 如何获取出现在特定 <h2> 之后的 <a href>?

javascript - Ant Design 如何设置图标大小?

html - CSS 动画首先失败然后按预期工作

javascript - 扩展 Accordion 列表项以保留在 flex 列中

html - 计算的宽度与指定的宽度有何不同?

HTML/CSS - 使用父 div 缩放图像

html - 使用float : left cause a change of length强制html元素并排定位