使第二个div首先出现在上面,没有绝对位置或更改html

时间:2014-12-09 07:40:29

标签: css css3

我的页面分为3个切片,如JFiddle所示。

在我的完整源代码中,我有媒体查询来帮助管理移动设备和桌面设备之间的大小调整。当有人在移动模式下访问该网站时,徽标显示在顶部显示在其下方 。 (我在我的图片div上设置display: none以隐藏它)

问题:

我无法在HTML中更改div的位置,或者它会干扰我当前的3切片布局。绝对定位不是一个选项,因为我的大多数网站已经动态调整大小,我不希望绝对定位干扰我尚未测试的分辨率。这意味着计算边际尺寸也是不可能的。

因此,不允许绝对定位,也不改变div的顺序。我正在寻找的结果类似于this,异常没有重新定位div。

我的问题不是媒体查询,也不是如何使用媒体查询调整移动设备的大小。我只询问如何获得我想要的布局和限制(没有绝对定位,没有计算边距,没有更改div顺序)。

我看过的其他问题:

Reposition div above preceding element - 第一个答案建议重新定位div,这是我做不到的。第二个答案依赖于计算位置,这可能会干扰其他动态尺寸元素。

Move The First Div Appear Under the Second One in CSS - 建议我使用绝对定位,这是我无法做到的

3 个答案:

答案 0 :(得分:41)

Flexbox布局是你的朋友。 display: flex可用于交换布局上的元素位置。

#container { display:flex; flex-direction: column; text-align:center;}
#items { order: 2 }
#logo { order: 1 }
#picture { display: none; }
<div id="container">
    <div id="items">Items</div>
    <div id="logo">Logo</div>
    <div id="picture">Picture</div>
</div>

display: flex仅适用于现代浏览器。检查caniuse

我的Android手机上的测试显示它可以在Firefox和Chrome上运行,但不会在Android浏览器上运行。

答案 1 :(得分:2)

我尝试使用百分比值中的transform: translateY属性来解决解决方案。

注意:当且仅当两个容器具有相同高度时,此方法才有效。或者如果已知高度,则可以根据高度设置transform: translateY值。

<强> CSS

@media (max-width: 700px) {
    #container > div {
        width: auto;
        display: block;
        float: none;
    }
    #container #picture {
        display: none;
    }
    #logo {
        transform: translateY(-100%);
    }
    #items {
        transform: translateY(100%);
    }
}

Working Fiddle

答案 2 :(得分:0)

可能最简单的是如果你使用负边距。请注意,可能需要根据您的特定需求调整以下尺寸(宽度和侧边距)。

#container * {
    width: 95vw;
    text-align: center;
}

#items {
    width: 50%; /* #picture is hidden so we split the screen into 2 */
    float: left;
    margin-top:30px; /* has to be smaller than the absolute of #logo */
    margin-left:25%; /* half of the element's width */
}

#logo {
    width: 50%; /* #picture is hidden so we split the screen into 2 */
    float: right;
    margin-top:-40px; /* its absolute has to be greater than the one of #items */
    margin-right:25%; /* half of the element's width */
}

#picture {
    width: 33%;
    float: right;
    display:none; /* Hiding #picture as you said you would */
}
<div id="container">
    <div id="items">Items</div>
    <div id="logo">Logo</div>
    <div id="picture">Picture</div>
</div>