我想创建一个div,它可以随着窗口宽度的变化而改变宽度/高度。

是否有任何CSS3规则允许高度根据宽度变化,同时保持其纵横比?

我知道我可以通过JavaScript做到这一点,但我更喜欢只使用CSS。


当前回答

只需创建一个包装器<div>,并为padding-bottom设置一个百分比值,如下所示:

.demoWrapper { 填充:10 px; 背景:白色; box-sizing: border-box; 调整:水平; 边框:1px虚线; 溢出:汽车; max-width: 100%; 高度:calc(100vh - 16px); } div { 宽度:100%; padding-bottom: 75%; 背景:黄金;/** <——用于演示**/ } < div class = " demoWrapper”> < div > < / div > < / div >

它将生成一个<div>,其高度等于其容器宽度的75%(4:3长宽比)。

这依赖于以下事实:

百分比是根据生成的盒子的包含块的宽度计算的[…](来源:w3.org,重点是我的)

其他纵横比和100%宽度的填充底部值:

aspect ratio  | padding-bottom value
--------------|----------------------
    16:9      |       56.25%
    4:3       |       75%
    3:2       |       66.66%
    8:5       |       62.5%

在div中放置内容:

为了保持div的纵横比并防止它的内容被拉伸,你需要添加一个绝对定位的子元素,并将其拉伸到包装器的边缘:

div.stretchy-wrapper {
  position: relative;
}

div.stretchy-wrapper > div {
  position: absolute;
  top: 0; bottom: 0; left: 0; right: 0;
}

这里有一个演示和另一个更深入的演示

其他回答

我偶然发现了这个问题的聪明解决方案,使用<svg>和display:grid。

一个display:grid元素允许您使用相同的网格区域,与它的两个(或更多)子元素占据相同的空间。 这意味着它们都是流内容,重叠在一起,并且高的那个设定了比例。

其中之一是负责设置比率的<svg>。另一个是实际内容。如果实际内容很短,并且永远不会占满整个比例(并且您只想让它以这个比例居中),只需将其居中(请参阅下面的第一个可运行代码片段)。

<div class="ratio">
  <svg viewBox="0 0 1 1"></svg>
  <div>
    I'm square
  </div>
</div>
.ratio {
  display: grid;
}
.ratio > * {
  grid-area: 1/1;
}

将<svg>的比率设置为您想要的任何值:

<svg viewBox="0 0 4 3"></svg> . <svg viewBox="0 0 16 9"></svg> .

.ratio { 显示:网格; } .ratio > * { 网格:1/1; } /*下面的代码不需要设置比例 我只是想在视觉上做个标记 *和中心内容 * / .ratio div { 边框:1px纯红色; 显示:flex; 对齐项目:中心; justify-content:中心; } < div class = "比" > <svg viewBox="0 0 7 1"></svg> . < div > 固定比例7:1 < / div > < / div >


如果你需要一个解决方案,其中内容元素有更多的内容,你想要限制在一个滚动区域与期望的比例,设置位置:相对的父位置:绝对;高度:100%;overflow-y:汽车;在内容上,允许流内容元素(<svg>)设置大小,因此设置比率。

.ratio { 显示:网格; 位置:相对; } .ratio > * { 网格:1/1; } .ratio > div { 高度:100%; overflow-y:汽车; 位置:绝对的; /*其余部分不需要*/ 边框:1px纯红色; 填充物:0 1rem; } < div class = "比" > <svg viewBox="0 0 7 2"></svg> . < div > <h1>固定比例7:2</h1> <p>痛苦的痛苦,神圣的解脱,痛苦的痛苦和巨大的痛苦。一个永恒的灵魂。扫描光晕直径,坐与nisl,疑,adipiscisbendum。一个永远的主人,一个生命的时刻,一个心灵的灵魂。Morbi enim nunc faucibus一个漂亮的坐遇见porttitor。Arcu odio ut sem nulla。在分娩的过程中。克拉巧合的叶状裂片,在augue eget。老爷子和老爷子坐着。我不知道你在说什么。狮子座,在生命的turpis massa, tempus element, estestas。est整数eget aliquet nibh。多洛尔与神圣的精英们会面。 <p>但aliquam purus sit meet。Eget magna fermentum iaculis eu non diam phasellus vestibulum。这是我的命运,我的命运。剥夺权利,剥夺权利,剥夺生命。移动门,非枕边边,老窝悬挂。在tellus在urna condimentum mattis pellentesque。圣歌,圣歌,圣歌。这是一种很好的方法。皮朗式的夹缝。Velit euismod in pellentesque massa placerat duis。这是我的生命。 <p>Mauris a diam maecenas sed enim ut sem。在怀孕的过程中。我的格言是我的,我的灵魂是我的。Urna porttitor rhoncus dolus purus non enim present。下丘脑大炎,下丘脑大炎。生命之箭,狮子座之箭。对车辆的不作为权,对生命的不作为权。Volutpat odio facilisis mauris sit amet massa vitae tortorcondimentum。Aliquam purus sit at the luctus venenatis lectus magna。坐下来,感受孕妇的痛苦。Enim eu turpis eggestas pretium aenean。不可预知的后果。在怀孕初期,永远没有生气。言归正传。Blandit massa enim nec dui nunc mattis enim ut。 < / div > < / div >


正如@emjay在下面的评论中指出的那样,ratio svg可以放在父元素的一个伪元素中,只要它被正确编码:

.three-squares { 显示:网格; 边框:1px纯红色; } .three-squares > *, .three-squares:before { 网格:1/1; } .three-squares:{之前 content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 3 1'%3E%3C/svg%3E"); 行高:0; } < div class = "抢走”> < div >我3:1 < / div > < / div >

当在伪元素中使用时,<svg>成为一个替换的元素,默认情况下,它位于可变高度的基线上(Chrome中为4px, Firefox中为3.5px)。基线的高度根据行高而变化,这就是为什么我们需要在pseudo上设置line-height: 0以获得准确的比率。详情请点击这里。


我个人更喜欢将<svg>放在标记中的版本,因为我可以用一个类(.ratio)处理各种比率的容器(而不是为我可能需要的每个比率使用一个类)。

假设你有2个div,外部的div是一个容器,内部的div可以是你需要保持其比例的任何元素(img或YouTube iframe或其他)

HTML看起来是这样的:

<div class='container'>
  <div class='element'>
  </div><!-- end of element -->
<div><!-- end of container -->

比如说你需要保持元素的比例 比例=> 4比1或2比1…

CSS是这样的

.container{
  position: relative;
  height: 0
  padding-bottom : 75% /* for 4 to 3 ratio */ 25% /* for 4 to 1 ratio ..*/
  
}

.element{
  width : 100%;
  height: 100%;
  position: absolute; 
  top : 0 ;
  bottom : 0 ;
  background : red; /* just for illustration */
}

当在%中指定填充时,它是基于宽度而不是高度计算的。 .. 所以基本上,不管你的宽是多少,高总是以此为基础计算出来的。这样就能保持比例不变。

在Angular中,我添加了一个处理纵横比的指令。

import { AfterViewInit, Directive, ElementRef, Input, Renderer2 } from 
"@angular/core";
import { debounceTime, fromEvent, Subject, takeUntil } from "rxjs";
 
// Auto sets the height of element based on width. Also supports window resize
@Directive({
    selector: '[aspectRatio]'
})
export class AspectRatioDirective implements AfterViewInit {
    @Input() aspectRatio?: number; // example 9/16

    private readonly onDestroy$ = new Subject<void>();

    constructor(private element: ElementRef, private renderer: Renderer2) {}

    public ngAfterViewInit(): void {
        this.setDimensions();
        this.initResizeListeners();
    }

    public ngOnDestroy(): void {
        this.onDestroy$.next();
        this.onDestroy$.complete();
      }

    private setDimensions(): void {
        if (!this.aspectRatio) { return; }
        const width = this.element.nativeElement.clientWidth;
        this.renderer.setStyle(this.element.nativeElement, 'height', `${width * this.aspectRatio}px`);
    }

    private initResizeListeners(): void {
        fromEvent(window, 'resize')
          .pipe(debounceTime(100), takeUntil(this.onDestroy$))
          .subscribe(() => this.setDimensions());
      }
}

这里是我的解决方案,以保持16:9纵横比在纵向或横向的div与可选的固定边距。

它是宽度/高度和最大宽度/最大高度属性与vw单位的组合。

在这个示例中,悬停时添加了50px的上下边距。

html { 高度:100%; } 身体{ 保证金:0; 高度:100%; } .container { 显示:flex; justify-content:中心; 对齐项目:中心; 高度:100%; } .fixedRatio { max-width: 100大众; Max-height: calc(9 / 16 * 100vw); 宽度:calc(16 / 9 * 100vh); 身高:100 vh; /*调试*/ 显示:flex; justify-content:中心; 对齐项目:中心; 背景颜色:蓝色; 字体大小:2快速眼动; 字体类型:“天线”; 颜色:白色; 过渡:宽度0.5s进出,高度0.5s进出; } .fixedRatio:{徘徊 宽度:calc(16 / 9 * (100vh - 100px)); 高度:calc(100vh - 100px); } < div class =“容器”> < div class = ' fixedRatio ' > 16:9 < / div > < / div >

在JSFiddle上演示

我遇到过这个问题很多次,所以我为它做了一个JS解决方案。这基本上是根据你指定的元素宽度比例来调整domElement的高度。你可以这样使用它:

<格比=“4x3”></div>

请注意,因为它正在设置元素的高度,元素应该是一个display:block或display:inline-block。

https://github.com/JeffreyArts/html-ratio-component