我使用Bootstrap 3做一个目录。当在平板电脑上显示时,产品图像看起来很难看,因为它们的尺寸很小(500x500),在浏览器中宽度为767像素。我想把图像放在屏幕的中央,但由于某种原因我不能。谁将帮助解决这个问题?


当前回答

到目前为止,接受的最佳解决方案似乎是<img class="center-block"…/ >。但是没有人提到过中央块是如何工作的。

以Bootstrap v3.3.6为例:

.center-block {
  display: block;
  margin-right: auto;
  margin-left: auto;
}

<img>的display默认值为inline。Value block将一个元素显示为块元素(如<p>)。它从一个新的行开始,并占用整个宽度。通过这种方式,两个边距设置让图像水平地保持在中间。

其他回答

您仍然可以使用img-responsive,而不影响使用此样式类的其他图像。

你可以在这个标签前面加上section id/ div id/class来定义一个img被嵌套的顺序。这个自定义的img-responsive将只在该区域工作。

假设你有一个HTML区域定义为:

<section id="work"> 
    <div class="container">
        <div class="row">
            <img class="img-responsive" src="some_image.jpg">
        </div>
    </div>
</section>

然后,你的CSS可以是:

section#work .img-responsive{
    margin: 0 auto;
}

注意:这个答案与整体改变img-responsive的潜在影响有关。当然,中心块是最简单的解决方案。

我建议采用更“抽象”的分类。添加一个新类"img-center",它可以和.img-responsive类结合使用:

// Center responsive images
.img-responsive.img-center {
  margin: 0 auto;
}

你可以在这里使用属性d-block,或者你可以在bootstrap中使用属性'text-center'或在css中使用'text-align: center'的父div。

图像默认显示为内联块,您需要将其显示为块以便以.mx-auto居中。这可以用内置的.d-block完成:

<div>
    <img class="mx-auto d-block" src="...">  
</div>

或者将其保留为内联块,并使用.text-center将其包装在div中:

<div class="text-center">
    <img src="...">  
</div>
<div class="text-align" style="text-align: center;  ">
    <img class="img-responsive" style="margin: auto;" alt="" src="images/x.png ?>">
</div>

你可以试试这个。

这应该使图像居中,并使其响应。

<img src="..." class="img-responsive" style="margin:0 auto;"/>