保持所有图像居中和分离

时间:2015-09-25 18:39:37

标签: html css html5 css3 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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:3)

您可以在所有窗口大小中保持所有三个图像的中心位置 - 垂直和水平 - 只需使用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的更多信息,请访问:

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

答案 1 :(得分:0)

  

如果您现在不想学习新的框架......这将调整图像的大小并将它们保持在中间位置。 vw代表视口宽度。 vh是视口高度单位。在这里,我们将确保无论窗口大小如何,图像将始终为屏幕的30%。高度始终是屏幕高度的20%。然后我们给第一张图像一个明确的边距来自最近的兄弟。混淆宽度,高度和第一个元素的上边距,以获得您想要的。   JSFiddle:https://jsfiddle.net/xrvustpa/或者你更喜欢https://jsfiddle.net/xrvustpa/3/。就像我说的。与价值观混淆。简洁明了。

<style>
    html, body {
        height: 100%;
        margin: 0;
        padding: 0;
        width: 100%;
    }
    body {
        display: table;
    }
    img {
        display: block;
        margin-right: auto;
        margin-left: auto;
        width: 30vw;
        height: 20vh;
    }

</style>


<div class="my-block">
    <img src="http://www.clker.com/cliparts/d/X/i/j/F/U/expences-button-png-hi.png" style="margin-top:20vh"/>
    <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>
相关问题