【问题标题】:Base percentage off height instead of width in css? [duplicate]CSS中高度而不是宽度的基本百分比? [复制]
【发布时间】:2018-07-25 14:23:08
【问题描述】:

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

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

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

注意:我的图片位于<div align="center"> 中以使其水平居中

【问题讨论】:

  • 如果没有更多上下文,很难确定最有效的方法。你可以为你的情况创建一个working example 吗?你可以考虑using flexbox
  • 基于百分比的填充是使元素居中的错误方法。 Maybe this article will help.
  • 不,您无法将计算百分比基值从宽度更改为高度。

标签: html css vertical-alignment


【解决方案1】:

你能用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

【讨论】:

    【解决方案2】:

    如果没有你想要做的事情的完整背景,我猜 CSS Flex 是你最好的选择。我附上的 sn-p 向您展示了一种在图像不是全尺寸背景时在 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>

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2013-08-23
        • 2012-02-20
        • 2021-03-03
        • 2014-06-07
        • 2014-03-05
        • 2012-12-17
        • 1970-01-01
        • 2014-04-22
        • 2015-01-13
        相关资源
        最近更新 更多