我想创建一个div,它可以随着窗口宽度的变化而改变宽度/高度。
是否有任何CSS3规则允许高度根据宽度变化,同时保持其纵横比?
我知道我可以通过JavaScript做到这一点,但我更喜欢只使用CSS。
我想创建一个div,它可以随着窗口宽度的变化而改变宽度/高度。
是否有任何CSS3规则允许高度根据宽度变化,同时保持其纵横比?
我知道我可以通过JavaScript做到这一点,但我更喜欢只使用CSS。
当前回答
我遇到过这个问题很多次,所以我为它做了一个JS解决方案。这基本上是根据你指定的元素宽度比例来调整domElement的高度。你可以这样使用它:
<格比=“4x3”></div>
请注意,因为它正在设置元素的高度,元素应该是一个display:block或display:inline-block。
https://github.com/JeffreyArts/html-ratio-component
其他回答
您可以通过使用SVG来实现这一点。
这要视情况而定,但在某些情况下它真的很有用。举个例子,你可以设置background-image而不设置固定的高度,或者用它来嵌入youtube <iframe>,比例为16:9,位置:绝对等。
对于3:2的比例设置viewBox="0 0 3 2"等等。
例子:
div { 背景颜色:红色 } svg { 宽度:100%; 显示:块; 可见性:隐藏 } .demo-1{宽度:35%} .demo-2{宽度:20%} < div class = " demo-1”> <svg viewBox="0 0 3 2"></svg> . < / div > <人力资源> < div class = " demo-2”> <svg viewBox="0 0 3 2"></svg> . < / div >
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;
}
在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());
}
}
如果你想在纵向视图或横向视图的视口中放置一个正方形(尽可能大,但没有任何东西粘在外面),在纵向/横向方向上切换使用vw/vh:
@media (orientation:portrait ) {
.square {
width :100vw;
height:100vw;
}
}
@media (orientation:landscape) {
.square {
width :100vh;
height:100vh;
}
}
CSS对此有一个新的属性:aspect-ratio。
https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio
@supports(纵横比:1 / 1){ div { 纵横比:16 / 9; 背景颜色:橙色; } } <div style="width: 200px"></div> . <人力资源/ > <div style="width: 400px"></div> . <人力资源/ > <div style="height: 50px"></div> . <人力资源/ > <div style="height: 10px"></div> .
Chrome和Edge从V88开始完全支持它,Firefox从V81开始支持它(设置layout.css.aspect-ratio。在about:config中启用为true)。
兼容性信息请访问https://caniuse.com/mdn-css_properties_aspect-ratio