使用css小于其内容的div背景(不指定%或px中的宽度)

时间:2013-07-24 01:04:19

标签: html css

这就是我所拥有的:

<div style="width: 100%; background: red; text-align: center">
  <img src="http://upload.wikimedia.org/wikipedia/commons/thumb/e/e5/Plain-M%26Ms-Pile.jpg/280px-Plain-M%26Ms-Pile.jpg" height="170" width="170" style="border-radius:700px; border: 10px solid white;">
</div>

这就是我想要的:

enter image description here

我在CSS中尝试了边框,插入阴影和许多其他选项,但它们似乎都不适用于我的目的。

有没有办法让div的背景小于内容而不必指定它的高度?

3 个答案:

答案 0 :(得分:1)

添加另一个div就可以了;

<div style="width: 100%; text-align: center">
  <div style="width:100%;height:100px;position:absolute;left:0;top:45px;background:red;z-index:-1;"></div>
  <img src="http://upload.wikimedia.org/wikipedia/commons/thumb/e/e5/Plain-M%26Ms-Pile.jpg/280px-Plain-M%26Ms-Pile.jpg" height="170" width="170" style="border-radius:700px; border: 10px solid white;">
</div>

答案 1 :(得分:1)

像这样(fiddle)?

div {
    margin: 40px 0;
}

img {
    margin: -40px 0;
}

答案 2 :(得分:0)

我知道这是旧的,但您可以使用背景大小和位置(如果需要)。

background-size: 50% 50%; /* background half the size of the div */
background-position: 50% 50%; /* to center it */
相关问题