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

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

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


当前回答

根据你的解决方案,我做了一些技巧:

当您使用它时,您的HTML将只有

<div data-keep-ratio="75%">
    <div>Main content</div>
</div>

用这种方法使: CSS:

*[data-keep-ratio] {
    display: block;
    width: 100%;
    position: relative;
}
*[data-keep-ratio] > * {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
}

jQuery和jQuery

$('*[data-keep-ratio]').each(function(){ 
    var ratio = $(this).data('keep-ratio');
    $(this).css('padding-bottom', ratio);
});

有了这个,你只需要设置attr data-keep-ratio到高/宽,就这样。

其他回答

2021年更新- CSS纵横比属性

我们最近获得了在CSS中使用长宽比属性的能力。

https://twitter.com/Una/status/1260980901934137345/photo/1

注意:支持还不是最好的…

注意:支持是相当体面的!

https://caniuse.com/#search=aspect-ratio

编辑:长宽比现在可用!

https://web.dev/aspect-ratio/

如果你对如何使用它感兴趣,可以看看下面这个超级简单的例子

    .yourClass {
       aspect-ratio: 4/3;
    }

如果你想在纵向视图或横向视图的视口中放置一个正方形(尽可能大,但没有任何东西粘在外面),在纵向/横向方向上切换使用vw/vh:

@media (orientation:portrait ) {
  .square {
    width :100vw;
    height:100vw;
  }
} 
@media (orientation:landscape) {
  .square {
    width :100vh;
    height:100vh;
  }
} 

我想只是使用rem或em应该解决固定比例的问题,但不会像vw或vh那样难以绑定到屏幕上,或者像%那样痛苦地使用flexbox。好吧,没有一个答案适合我,在我的情况下,这对我来说很重要:

<div class="container">
   <div>
   </div>
</div>
.container {
   height: 100vh;
   width: 100vw;
}
.container div {
   height: 4em;
   width: 3em;
}

或者用rem,但是不管怎样,它们中的任何一个都可以。 Rem使用默认的字体大小值,而em使用最接近的字体大小。

我刚刚创建了一个2:1的div,调整大小以占据全宽度,但如果它会导致顶部或底部超过,则会缩小宽度。但是请注意,这只适用于窗口的大小,而不是父窗口的大小。

#scene {
    position: relative;
    top: 50vh;
    left: 50vw;
    width: 100vw;
    height: 50vw;
    max-height: 100vh;
    max-width: calc(100vh * 2);
    transform: translate(-50%, -50%);
}

我相信你可以计算出正确的%,用于4:3而不是2:1。

在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());
      }
}