我想创建一个div,它可以随着窗口宽度的变化而改变宽度/高度。
是否有任何CSS3规则允许高度根据宽度变化,同时保持其纵横比?
我知道我可以通过JavaScript做到这一点,但我更喜欢只使用CSS。
我想创建一个div,它可以随着窗口宽度的变化而改变宽度/高度。
是否有任何CSS3规则允许高度根据宽度变化,同时保持其纵横比?
我知道我可以通过JavaScript做到这一点,但我更喜欢只使用CSS。
当前回答
2022解决方案-使用CSS的纵横比属性
<div class='demo'></div>
.demo {
background: black;
width: 500px;
aspect-ratio: 4/3;
}
更新:现在所有常绿浏览器都支持这个解决方案
其他回答
实际上,高投票的答案是一个非常好的解决方案,但有一个新的CSS功能,名字是长宽比。
它可以这样使用:
.someClass {
width: 100%;
aspect-ratio: 4/3;
}
自动确定高度,但请参见兼容性表:
如果浏览器支持对你的项目很重要,不要使用它。使用填充底技术。
我遇到过这个问题很多次,所以我为它做了一个JS解决方案。这基本上是根据你指定的元素宽度比例来调整domElement的高度。你可以这样使用它:
<格比=“4x3”></div>
请注意,因为它正在设置元素的高度,元素应该是一个display:block或display:inline-block。
https://github.com/JeffreyArts/html-ratio-component
在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());
}
}
只是一个想法或黑客。
div { 背景颜色:蓝色; 宽度:10%; 过渡:底色0.5s,宽度0.5s; 字体大小:0; } div:{徘徊 宽度:20%; 背景颜色:红色; } img { 宽度:100%; 高度:汽车; 可见性:隐藏; } < div > <!—使用具有目标纵横比的图像。样本是一个正方形——> <img src="http://i.imgur.com/9OPnZNk.png" /> < / 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;
}