【问题标题】:How to vertically center an image and make it fill available width如何垂直居中图像并使其填充可用宽度
【发布时间】:2016-10-17 01:36:31
【问题描述】:

我正在尝试制作一个简单的网页,该网页显示尽可能大但位于页面中心的 GIF。我希望图像垂直居中。这是JSFiddle 的链接。

<!DOCTYPE html>
<html>
<head>
    <title>Gandalf Sax Guy!</title>
</head>
<body>
<style>

body {
    overflow: hidden;
    background-color: black;
    margin: 0;
}

img {
    width: 100%;
    height: 100%;
}

</style>

    <img src="http://eul.ddns.net/gandalf/gif.gif"/>

    <audio autoplay sr>
        <source src="http://eul.ddns.net/gandalf/sax.mp3">
    </audio>

我希望图像尽可能大,但不失真,并且可以动态工作。

如您所见,我希望图像上方和下方有相同数量的“黑色空间”。

【问题讨论】:

  • 您的编辑应该是根据塞巴斯蒂安的回答做出的评论回复,而不是对您的问题的编辑。 :-)
  • 好的,下次我会尽量记住这一点。也感谢您解决我的问题!

标签: html css image vertical-alignment


【解决方案1】:

translate(-50%) 方法,更多信息见 cmets

img {
  position: absolute;
  top: 50%; left: 50%; 
  /* the above combined with translate -50% will..
  center it horizontally and vertically */
  transform: translate(-50%, -50%);
  width: initial; /* no width setting will size it as its original size */
  width: 100%; /* control image size based on screen width */
  width: 50%; /* try all 3 to see */
  width: 17%;
  /* dont mess with height and it will scale with the width */
  /* or only adjust height and let image width scale to it */
  /* height: 100%; */
}
&lt;img src="https://i.stack.imgur.com/Dpd0U.jpg?s=48&amp;g=1"&gt;

CSS Tricks 有一篇很棒的文章,介绍了不同的居中方法。

https://css-tricks.com/centering-css-complete-guide/

fiddle to play with

【讨论】:

    【解决方案2】:

    flexbox 来救援!

    #positioning-context {
      display: flex;
      align-items: center;
      justify-content: center;
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
    }
    <div id="positioning-context">
      <img src="https://placekitten.com/140/50" />
    </div>

    【讨论】:

    • 谢谢!我尝试了 flexbox 方法,但它并没有发生在我身上。现在我只需要让它尽可能地填满屏幕。你会如何建议这样做?再次感谢!
    • 感谢@KhrisAzuaje,虽然这在一定程度上有效,但图像并没有保持其原始纵横比并且失真。有什么办法解决吗?
    • 你用的是什么浏览器?这样做的目的是什么?元素的大小会不断变化吗?无论您如何执行此操作,您都可能需要图像调整器,如果元素调整大小大于或小于图像原始大小,它将显示失真。我认为 Chrome 会自行调整图像大小,但其他浏览器不会。如果这是用于服务器,可以说显示用户选择的背景或类似的东西 Id 推荐 PHP imageresizer
    • 再次阅读我的回答,希望对您有所帮助,如果没有:请告诉我更多关于您想要实现的目标,我们会想办法解决的。
    猜你喜欢
    • 1970-01-01
    • 2011-11-24
    • 2011-10-01
    • 1970-01-01
    • 2016-12-01
    • 2011-09-11
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    相关资源
    最近更新 更多