Flexbox,方形div的响应式网格,保持长宽比 [英] Flexbox, responsive grid of square divs maintaining aspect ratio

查看:99
本文介绍了Flexbox,方形div的响应式网格,保持长宽比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用div创建2x2网格.某些div可能包含图像,但可能会将其设置为背景,并带有background-size: cover选项.

I'm trying to create a 2x2 grid with divs. Some of the divs might contain an image, but it will probably be set as a background, with the option background-size: cover.

这是我创建的笔: http://codepen.io/qarlo/pen/vLEprq

.container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  margin: auto;
  max-width: 960px;
  width: 80%;
}
.container__item {
  align-content: center;
  border: 1px solid #333;
  display: flex;
  flex-basis: 1;
  font-size: 3em;
  justify-content: center;
  height: 100%;
  margin-bottom: 1em;
  min-height: 300px;
  width: 47%;
}

<div class="container">
  <div class="container__item">?</div>
  <div class="container__item">?</div>
  <div class="container__item">?</div>
  <div class="container__item">?</div>
</div>

在调整大小时,我想强制将div设为正方形并保持宽高比.我错误地希望Flexbox能够做到这一点很简单,但是除非我丢失了某些东西,否则我是错的.

I'd like to force the divs to be squares and maintain the aspect ratio when resizing it. I was mistakenly hoping that this would have been straightforward with flexbox, but unless I'm missing something, I was wrong.

推荐答案

要保持商品的长宽比,一种非常简单的方法是使用

To maintain your items aspect ratio, a very simple method is to use CSS Viewport units

我修改了您的笔以查看其工作原理: http://codepen.io/vladbicu/pen/wMBmOb

I modified your pen to see how this units work: http://codepen.io/vladbicu/pen/wMBmOb

.container {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    margin: auto;
    max-width: 960px;
    width: 80%;
}

.container__item {
    align-content: center;
    border: 1px solid #333;
    display: flex;
    flex-basis: 1;
    font-size: 3em;
    justify-content: center;
    margin-bottom: 1em;

    // maintain aspect ratio
    width: 30vw;
    height: 30vw;
}

希望有帮助.

这篇关于Flexbox,方形div的响应式网格,保持长宽比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆