保留CSS网格中的宽高比

时间:2017-01-25 18:51:37

标签: html css grid-layout aspect-ratio

我正在尝试实现包含3x4元素的响应式网格。我还为每个单元格使用位图图像,因此我想保留每个单元格的纵横比。我现在遇到的问题是,我的CSS并不能防止它溢出视口的垂直大小。在水平轴上缩放时,它可以正常工作。

按预期工作: Works as expected

没有按预期工作(创建滚动条): Doesn't work as expected

指向CodePen的链接:http://codepen.io/ekulabuhov/pen/JEyxby?editors=1100



.container{
  height:100vm; width:100vm; /* IE9 fallback */
  width: 100vmin; height: 100vmin;
  position: absolute;
  top:0;bottom:0;
  left:0;right:0;
  margin: auto;
}

.gametile {
  background: url('http://adrianpayne.me/game/assets/images/grass.png') no-repeat; 
  background-size: cover;

  /* 33.3vmin; */
  width: calc(100vmin/3);
  float:left;
  height: calc(100vmin/3*(91/70));
  margin-top: -16vmin;
}


/*** FOR THE DEMO **/
body,html {margin:0;background:#123752;color:#fff;}
a{color:#ccc;}

<div class="container">
  <div class="gametile"></div>
  <div class="gametile"></div>
  <div class="gametile"></div>
  
  <div class="gametile"></div>
  <div class="gametile"></div>
  <div class="gametile"></div>
  
  <div class="gametile"></div>
  <div class="gametile"></div>
  <div class="gametile"></div>

  <div class="gametile"></div>
  <div class="gametile"></div>
  <div class="gametile"></div>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

我玩弄了这些值并设法将其置于屏幕中心而不会超出界限。

.container{
  height:60vm; width:100vm; /* IE9 fallback */
  width: 100vmin; height: 60vmin;
  position: absolute;
  top:0;bottom:0;
  left:0;right:0;
  margin: auto;


}

.gametile {
  background: url('http://adrianpayne.me/game/assets/images/grass.png') no-repeat; 
  background-size: cover;

  /* 33.3vmin; */
  width: calc(80vmin/3);
  float:left;
  height: calc(80vmin/3*(91/70));
  margin-top: -16vmin;
}

答案 1 :(得分:1)

&#13;
&#13;
.container{
  height:100vm; width:100vm; /* IE9 fallback */
  width: calc(((100vmin - 16vmin) / 4 + 16vmin) * (70 / 91) * 3);
  height: 100vmin;
  position: absolute;
  top:0;bottom:0;
  left:0;right:0;
  margin: auto;
}

.gametile {
  background: url('http://adrianpayne.me/game/assets/images/grass.png') no-repeat; 
  background-size: cover;

  /* 33.3vmin; */
  width: calc(100% / 3);
  float:left;
  height: calc((100% - 16%) / 4 + 16%);
  margin-bottom: -16vmin;
}


/*** FOR THE DEMO **/
body,html {margin:0;background:#123752;color:#fff;}
a{color:#ccc;}
&#13;
<div class="container">
  <div class="gametile"></div>
  <div class="gametile"></div>
  <div class="gametile"></div>
  
  <div class="gametile"></div>
  <div class="gametile"></div>
  <div class="gametile"></div>
  
  <div class="gametile"></div>
  <div class="gametile"></div>
  <div class="gametile"></div>

  <div class="gametile"></div>
  <div class="gametile"></div>
  <div class="gametile"></div>
</div>
&#13;
&#13;
&#13;

不知道它是否在IE9中有效,但我已经为你修复了它。它可能不会在IE中工作。如果您放弃旧浏览器,也可以尝试display: grid