[英]Why isn't my image centered in the div?
Can anyone tell me why this doesn't work? 谁能告诉我为什么这行不通? I'm trying to center the image.
我正在尝试将图像居中。
CSS CSS
.img-center {
display: block;
margin-left: auto;
margin-right: auto;
}
HTML HTML
<div class="container">
<section id="whats-on">
<h1>News</h1>
<div class="img-center">
<a href="#"><img src="assets/img/my-image.png"></a>
</div>
</section>
</div><!-- container -->
the img-center
container has width 100% ( by default ) so it is already centered but covers the width of all the viewport . img-center
容器的宽度为100%(默认情况下),因此它已经居中,但覆盖了所有视口的宽度。 this is because a div
is a block
element and as the DOCumentation says 这是因为
div
是一个block
元素,正如DOCumentation所说
A block-level element always starts on a new line and takes up the full width available (stretches out to the left and right as far as it can).
块级元素总是从新行开始,并占据可用的全部宽度(尽可能向左和向右伸展)。 The
<div>
element is a block-level element.<div>
元素是块级元素。
so you can remove the display:block
因此您可以删除
display:block
option A. add text-align:center
to .img-container
选项A.将
text-align:center
添加到.img-container
for this option you can remove all other styles 对于此选项,您可以删除所有其他样式
.img-center { text-align:Center; }
<div class="container"> <section id="whats-on"> <h1>News</h1> <div class="img-center"> <a href="#"><img src="http://placehold.it/350x150"></a> </div> </section> </div><!-- container -->
option B. give the styles to the img
not to it's container 选项B.将样式赋予
img
而不是容器
for this option you need to keep the display:block
to the img
because img
is an inline
element by default 对于此选项,您需要将
display:block
保留在img
因为img
默认情况下是inline
元素
.img-center img { display: block; margin-left: auto; margin-right: auto; }
<div class="container"> <section id="whats-on"> <h1>News</h1> <div class="img-center"> <a href="#"><img src="http://placehold.it/350x150"></a> </div> </section> </div><!-- container -->
Just Simply add text-align: center;
只需添加
text-align: center;
to .img-center 到.img-center
This has to do with your <div class="img-center">
not having a set width. 这与您的
<div class="img-center">
没有设置宽度有关。 Add width:100px;
添加
width:100px;
just to see. 只是看看。
See this : https://jsfiddle.net/s3x82hv4/ 看到这个: https : //jsfiddle.net/s3x82hv4/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.