使div看起来好像它漂浮在它的容器之外

时间:2014-02-28 19:48:10

标签: html css css-float css-position

我正试图让div(里面有背景图片)看起来漂浮在它的容器之外。我对内容div中的图像重叠内容很好,但我不希望图像或容器与其他内容重叠。我也不希望图像推动内容。

我正在做的事情看起来很糟糕,我可以通过设置一堆自定义的顶部和底部边距来修复重叠,但我确信有一种更简单的方法可以做到这一点。

http://codepen.io/0bsidian/pen/GdwhF

2 个答案:

答案 0 :(得分:2)

这里你需要的是box-shadow的想法。

div {
  box-shadow: 2px 2px 5px #333;
}

您可以使用自己的这些参数。这样,您可以使元素看起来像是浮动在另一个元素上。

更多信息:https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow

答案 1 :(得分:1)

我看了你的代码。 (注意,为了将来参考,请使用代码括号在此处附上您的代码。这将在以后的情况下证明代码栈关闭时的问题)。您要将父换行设置为position:relative,将任性的孩子设置为position:absolute

这样可行,但你说得对,方法更简单。只需将孩子设置为position:relative,然后确保父级没有overflow:hidden

编辑:你不需要任何亲戚或绝对,你可以只使用边距。我试图分叉你的代码链接,但它不会让我。所以这是代码:

body {
    background: #444;
}
section {
    width: 600px;
    margin: 6em auto 0 auto;
}
#container {
    margin-top:50px; /*30px would make it touch the <p> above but not overlap, because the image is moved upwards by 30px. 50px gives you a 20px margin.*/
}
#container #image {
    height: 128px;
    width: 128px;
    background: url(http://www.skrenta.com/images/stackoverflow.jpg) no-repeat;
    background-size: contain;
    float:left;
    margin-left:-30px;
    margin-top:-30px;
}
#container #content {
    margin-top:0px;
    padding: 6em 1em 1em 1em;
    border: 2px solid black;
    background: #ccc;
}
<html>
    <body>
        <section>
            <p>Stuff outside of container.</p>
            <div id="container">
                <div id="image"></div>
                <div id="content">
                    <h1>Test One</h1>
                    <p>This is a text box. Insert some text here.</p>
                    <p>More stuff here.</p>
                </div>
            </div>
            <p>Stuff outside of container.</p>
        </section>
    </body>
</html>

相关问题