具有平方比和 flexbox 的内部 div [英] Inner div with square ratio and flexbox

查看:13
本文介绍了具有平方比和 flexbox 的内部 div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力实现以下目标:

其中蓝色框的高度可变,而黄色框的高度始终为蓝色框的 50%.

使用 flex 相当简单

<div id="yellow" style="height:50%">

问题是我试图保持内盒的特定比例,在这种情况下是正方形.我该如何处理?

<小时>

奖励积分:

  • 我通常如何指定比率?有没有一种解决方案不仅适用于 1:1,还适用于任何 x:y?
  • 在不使用 flexbox 的情况下,我将如何做到这一点,同时可能仍以 a) 为目标?
<小时>

额外信息:蓝色框总是宽于高,想想按钮.

解决方案

与 Temani Afif 提供的答案类似,但使用 svg 而不是图像(因此无需额外请求).

此外,它更容易适应任意纵横比

.container {高度:150px;背景颜色:浅蓝色;显示:弹性;对齐项目:居中;对齐内容:居中;边距:10px;}.纵横比{显示:网格;背景颜色:黄色;高度:50%;}.aspectRatio SVG {高度:100%;边框:实心 1px 红色;动画:无限调整 1 秒;}.纵横比>* {网格区域:1/1/2/2;}@keyframes 调整大小 {从{高度:100%;}到{高度:99.9%;}}

<div class="aspectRatio"><svg viewBox="0 0 1 1"></svg><div class="inner">square</div>

<div class="容器"><div class="aspectRatio"><svg viewBox="0 0 4 3"></svg><div class="inner">ratio 4/3</div>

Im trying to achieve the following:

Where the blue box is of variable height and the yellow box is always of height 50% of the blue box.

Its fairly simple using flex

<div style="display:flex;align-items:center">
    <div id="yellow" style="height:50%">
    </div>
</div>

The problem is that im trying to keep the inner box a specific ratio, in this case square. How do i approach this?


Bonus points:


Extra information: The blue box is always wider than higher, think a button.

解决方案

A similar answer to the one provided by Temani Afif, but using an svg instead of an image (so no need to the extra request).

Also, it's easier to adapt it to arbitrary aspect ratios

.container {
  height: 150px;
  background-color: lightblue;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 10px;
}

.aspectRatio {
  display: grid;
  background-color: yellow;
  height: 50%;
}
.aspectRatio svg {
  height: 100%;
  border: solid 1px red;
  animation: resize 1s infinite;
}
.aspectRatio > * {
  grid-area: 1 / 1 / 2 / 2;
}

@keyframes resize {
  from {height: 100%;}
  to {height: 99.9%;}
}

<div class="container">
  <div class="aspectRatio">
    <svg viewBox="0 0 1 1"></svg>
    <div class="inner">square</div>
  </div>
</div>
<div class="container">
  <div class="aspectRatio">
    <svg viewBox="0 0 4 3"></svg>
    <div class="inner">ratio 4/3</div>
  </div>
</div>

这篇关于具有平方比和 flexbox 的内部 div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆