【问题标题】:How to center image which is bigger than screen?如何将比屏幕大的图像居中?
【发布时间】:2014-10-28 08:04:38
【问题描述】:

我有以下代码:

HTML

<div class="banner">
    <img src="banner.png">
</div>

CSS

.banner > img {
    margin: auto;
}

图片的宽度为 3000 像素,高度为 200 像素 我希望图像水平居中并且没有水平滚动条。 (浏览器调整大小应该没问题)

我尝试将横幅图像作为背景图像提供给.banner div,但是 div 不会自动找到它的大小...

这怎么可能?

【问题讨论】:

  • 如果你设置了背景,那么你可以使用 30x2 的透明图像并将其设置为 100% 的宽度,这样它就会为 div 占用正确的空间量
  • 如果您需要使用&lt;img&gt;,请查看我标记为的副本。如果可以使用背景图片,请尝试使用 CSS 背景图片进行background-size: cover
  • nicogaldo 的答案描述了我正在搜索的内容,但谢谢。也很有用!

标签: html css image center


【解决方案1】:
<div class="banner">
</div>

css:

.banner {
    background: url(http://ximg.es/3000x200/000/fff.png) no-repeat 50% 50%;
    height:200px;
}

像这样:jsfiddle

【讨论】:

  • 但我用center代替50% 50%
【解决方案2】:

您最好的选择是使用图像作为背景,但如果您想/需要使用图像,请这样做

.banner{overflow:hidden; height:200px; width:100%; text-align:center;}
.banner img{width:100%; height:100%; margin:0 auto;}

【讨论】:

  • 我不想在 css 中设置图像的确切大小。应该是动态的
  • 您在帖子中提到了固定尺寸。无论如何,为此,更好的方法是使用图像作为背景,就像我提到的和其他人所做的那样
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-19
  • 1970-01-01
  • 2016-07-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多