我有这个css:
<style type="text/css">
#heading{
margin:auto;
background-color: brown;
}
</style>
和这个html:
<div id="heading">
<image src="image_files/header-background.jpg" alt="speakom" />
</div>
我不知道图片的确切尺寸。。但是我希望div以精确的宽度包裹图像,然后我想将div居中。我该如何实现呢?
使用inline-block
将使div的宽度等于其内容的宽度,并允许您使用自动边距将其居中:
#heading {
margin: 0px auto;
display: inline-block;
}
这样写:
.parent{
text-align:center;
}
#heading{
display:inline-block;
*display:inline;/* For IE7*/
*zoom:1/* For IE7*/
text-align:left;
}
HTML
<div class="parent">
<div id="heading">
<img src="image_files/header-background.jpg" alt="speakom" />
</div>
</div>
检查这个http://jsfiddle.net/sAYEq/
获取
margin: auto;
声明要想像你想要的那样工作,你需要为div指定一个宽度。在不知道图像大小的情况下,你只需要猜测它是什么,或者使用javascript
根据我的经验,Dave的回答不起作用。我的首选解决方案使用flexbox:
<article>
<figure>
<img src="https://placekitten.com/300/200" />
<figcaption>Cute!</figcaption>
</figure>
</article>
article {
display: flex;
flex-direction: column;
}
figure {
margin: 0 auto;
background-color: lightgray;
}
figcaption {
padding: 1em;
}
您可以在https://codepen.io/marcvangend/pen/vPBVOv.
优点:
- 居中的元素(此处为
<figure>
)紧紧地包裹在图像周围 - 内部的所有元素(此处为:
<img>
、<figcaption>
)都具有相同的宽度 - 因为我们没有使用
text-align: center
,所以figcaption中的文本保持左对齐