【问题标题】:Size an image to full height or width depending on it's orientation?根据图像的方向将图像大小调整为全高或全宽?
【发布时间】:2016-08-02 23:01:59
【问题描述】:

我需要一张图片列表,我不知道图片的大小,有些可能是横向的,有些可能是纵向的。

横向的应该适合父 li 的 100% 宽度,纵向的应该适合 100% 的高度。

我可以开始工作的唯一方法是确定图像是横向还是纵向服务器端,并添加一个相关的类,这反过来会使宽度为 100% 或高度为 100%。

有没有办法做到这一点,保持纵横比,而不使用对象匹配或背景图像?

【问题讨论】:

  • 我不知道。 CSS 无法检测 size 因此它无法确定图像是横向还是纵向。那就是 JS的用途。

标签: html css


【解决方案1】:

max-heightmax-width 用于图像。您还可以将它们居中,这样小图像看起来会很好。

ul {
  margin: 0;
  padding: 20px;
  list-style: none;
  }
li {
  width: 100px;
  height: 100px;
  float: left;
  border: 1px dashed red;
  margin: 0 20px 20px 0;
  }
img {
  max-width: 100%;
  max-height: 100%;
  }
<ul>
  <li><img src="https://pixabay.com/static/uploads/photo/2015/02/08/20/57/man-629062_960_720.jpg" alt=""></li>
  <li><img src="https://pixabay.com/static/uploads/photo/2016/01/08/15/21/man-1128277_960_720.jpg" alt=""></li>
</ul>

【讨论】:

    【解决方案2】:

    如果我理解正确,这应该可以;

    jsFiddle

    <li class="container">
      <div class="landscape">
    
      </div>
    </li>
    <li class="container">
      <div class="portrait">
    
      </div>
    </li>
    
    
    .landscape {
      background-image:url("http://www.thelogofactory.com/wp-content/uploads/2015/09/fixed-google-logo-font.png");
      width: 100%;
      height: 100%;
      background-size: contain;
      background-repeat: no-repeat;
    }
    
    .portrait {
      background-image:url("https://developers.google.com/safe-browsing/images/SafeBrowsing_Icon.png");
      width: 100%;
     height: 100%;
     background-size: contain;
     background-repeat: no-repeat;
    }
    
    .container {
     width: 100px;
     height: 100px;
    }
    

    你可以用img标签代替div。

    【讨论】:

    • 谢谢,但问题说明没有背景图片。
    • 我怎么知道图像是纵向还是横向,您的回答基本上说明了我已经尝试过的内容。
    • 我认为您不能仅使用 CSS 来确定它。您可以在 Javascript 中编写一个函数来确定这一点,这比服务器端方法更好。
    猜你喜欢
    • 2017-07-14
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2014-03-20
    • 2014-01-16
    相关资源
    最近更新 更多