css 中基于高度而不是宽度的基本百分比?

Base percentage off height instead of width in css?

我在页面中有以下 css 始终使我的图片居中:

img {
        padding: calc(49% - 306px);
    }

我遇到的问题是“49%”是基于页面宽度,而不是我想要的高度。有什么办法可以改变吗?谢谢!

注意:我的图片在<div align="center">水平居中

您可以将 img 元素更改为 div 并将图像作为背景图像,如下所示:

div {
   width:100%; 
   height:100%; 
   background:url(logo.png) center center no-repeat;
 }

如果不了解您要执行的操作的完整上下文,我猜 CSS Flex 是您最好的选择。我附上的代码片段向您展示了一种方法,当图像不是全尺寸背景时,将图像居中放置在 div 中。

请记住,此解决方案需要针对您的应用程序进行一些修改。

.container {
  border:1px solid red;
  margin:0 auto;
  display:flex;
  height:500px;
  width:500px;
  justify-content:center;
  align-items:center;
}     
<div class="container">

  <img src="https://www.w3schools.com/howto/img_fjords.jpg" width="100px" height="100px">
  
</div>

可以使用flexbox吗?

html, body, div.center {margin: 0;height: 100%;}
div.center {display:flex; align-items: center;}

img {
  flex: 0 0 auto;
  margin: auto;
}
<div class="center">
  <img src="//placehold.it/306x100" alt="">
</div>

演示:http://output.jsbin.com/xotupegove