使用CSS维护div的纵横比

时间:2022-08-27 10:16:14

I want to create a div that can change its width/height as the window's width changes.

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

Are there any CSS3 rules that would allow the height to change according to the width, while maintaining its aspect ratio?

是否有CSS3规则允许高度随宽度变化,同时保持高宽比?

I know I can do this via JavaScript, but I would prefer using only CSS.

我知道我可以通过JavaScript实现,但我更喜欢使用CSS。

使用CSS维护div的纵横比

18 个解决方案

#1


1057  

Just create a wrapper <div> with a percentage value for padding-bottom, like this:

只需创建一个包装器

,其值为桨底的百分比值,如下所示:

div {
  width: 100%;
  padding-bottom: 75%;
  background: gold; /** <-- For the demo **/
}
<div></div>

It will result in a <div> with height equal to 75% of the width of its container (a 4:3 aspect ratio).

它将导致

,其高度等于其容器宽度的75%(4:3纵横比)。

This relies on the fact that for padding :

这依赖于如下事实:

The percentage is calculated with respect to the width of the generated box's containing block [...] (source: w3.org, emphasis mine)

这个百分比是根据生成的包含块的盒子的宽度来计算的。[来源:w3。org,强调我的)

Padding-bottom values for other aspect ratios and 100% width :

其他纵横比和100%宽度的划底值:

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

Placing content in the div :

在div中放置内容:

In order to keep the aspect ratio of the div and prevent its content from stretching it, you need to add an absolutely positioned child and stretch it to the edges of the wrapper with:

为了保持div的长宽比,防止其内容拉伸,需要添加一个绝对定位的子元素,将其拉伸到包装的边缘,如下所示:

div.stretchy-wrapper {
  position: relative;
}

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

Here's a demo and another more in depth demo

这是一个演示和另一个更深入的演示

#2


320  

vw units:

You can use vw units for both the width and height of the element. This allows the element's aspect ratio to be preserved, based on the viewport width.

你可以使用大众单位的宽度和高度的元素。这使得元素的纵横比得以保留,基于视窗宽度。

vw : 1/100th of the width of the viewport. [MDN]

大众:视场宽度的百分之一。(MDN)

Alternatively, you can also use vh for viewport height, or even vmin/vmax to use the lesser/greater of the viewport dimensions (discussion here).

或者,您也可以使用vh表示viewport高度,甚至vmin/vmax表示viewport维度的较小/较大(这里讨论)。

Example: 1:1 aspect ratio

div {
  width: 20vw;
  height: 20vw;
  background: gold;
}
<div></div>

For other aspect ratios, you can use the following table to calculate the value for height according to the width of the element :

对于其他纵横比,可以使用下表根据元素的宽度计算高度值:

aspect ratio  |  multiply width by
-----------------------------------
     1:1      |         1
     1:3      |         3
     4:3      |        0.75
    16:9      |       0.5625

Example: 4x4 grid of square divs

body {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
div {
  width: 23vw;
  height: 23vw;
  margin: 0.5vw auto;
  background: gold;
}
<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>

Here is a Fiddle with this demo and here is a solution to make a responsive grid of squares with verticaly and horizontaly centered content.

这是演示的一部分,这是一个解决方案,用垂直和水平居中的内容创建一个响应性的正方形网格。


Browser support for vh/vw units is IE9+ see canIuse for more info

vh/vw部件的浏览器支持是IE9+,更多信息请参见canIuse

#3


25  

I've found a way to do this using CSS, but you have to be careful as it may change depending on the flow of your own web site. I've done it in order to embed video with a constant aspect ratio within a fluid width portion of my web site.

我已经找到了一种使用CSS的方法,但是你必须小心,因为它可能会根据你自己网站的流量而变化。我这样做是为了在我的网站的流体宽度部分嵌入具有恒定长宽比的视频。

Say you have an embedded video like this:

假设你有这样一个嵌入式视频:

<object>
     <param ... /><param ... />...
     <embed src="..." ...</embed>
</object>

You could then place this all inside a div with a "video" class. This video class will probably be the fluid element in your website such that, by itself, it has no direct height constraints, but when you resize the browser it will change in width according to the flow of the web site. This would be the element you are probably trying to get your embedded video in while maintaining a certain aspect ratio of the video.

然后,您可以将所有这些放在带有“video”类的div中。这个视频类很可能是你网站的流体元素,它本身没有直接的高度限制,但是当你调整浏览器的大小时,它会根据网站的流量变化。这可能是你想要嵌入视频的元素,同时保持视频的一定长宽比。

In order to do this, I put an image before the embedded object within the "video" class div.

为了做到这一点,我将一个图像放在“video”类div中嵌入的对象之前。

!!! The important part is that the image has the correct aspect ratio you wish to maintain. Also, make sure the size of the image is AT LEAST as big as the smallest you expect the video (or whatever you are maintaining the A.R. of) to get based on your layout. This will avoid any potential issues in the resolution of the image when it is percentage-resized. For example, if you wanted to maintain an aspect ratio of 3:2, don't just use a 3px by 2px image. It may work under some circumstances, but I haven't tested it, and it would probably be a good idea to avoid.

! ! !重要的是图像有你希望维护的正确的纵横比。此外,确保图像的大小至少与您希望视频(或任何您正在维护的内容)根据布局得到的最小大小一样大。这将避免在调整百分比大小时在图像分辨率中出现的任何潜在问题。例如,如果你想保持3:2的长宽比,不要只使用3px * 2px的图像。它可能在某些情况下有效,但我还没有测试过它,所以最好避免它。

You should probably already have a minimum width like this defined for fluid elements of your web site. If not, it is a good idea to do so in order to avoid chopping elements off or having overlap when the browser window gets too small. It is better to have a scroll bar at some point. The smallest in width a web page should get is somewhere around ~600px (including any fixed width columns) because screen resolutions don't come smaller unless you are dealing with phone-friendly sites. !!!

您可能已经为web站点的流体元素定义了这样的最小宽度。如果不是,那么最好这样做,以避免在浏览器窗口太小时将元素截断或重叠。最好在某个点设置一个滚动条。一个网页的最小宽度应该在600像素左右(包括任何固定宽度的列),因为屏幕分辨率不会变小,除非你是在处理手机友好的网站。! ! !

I use a completely transparent png but I don't really think it ends up mattering if you do it right. Like this:

我使用的是完全透明的png,但我认为如果你做得对,它最终并不重要。是这样的:

<div class="video">
     <img class="maintainaspectratio" src="maintainaspectratio.png" />
     <object>
          <param ... /><param ... />...
          <embed src="..." ...</embed>
     </object>
</div>

Now you should be able to add CSS similar to the following:

现在您应该能够添加类似以下的CSS:

div.video { ...; position: relative; }
div.video img.maintainaspectratio { width: 100%; }
div.video object { position: absolute; top: 0px; left: 0px; width: 100%; height: 100%; }
div.video embed {width: 100%; height: 100%; }

Make sure you also remove any explicit height or width declaration within the object and embed tags that usually come with copy/pasted embed code.

确保您还删除了对象中的任何显式高度或宽度声明,并嵌入通常带有复制/粘贴嵌入代码的标记。

The way it works depends on the position properties of the video class element and the item you want have maintain a certain aspect ratio. It takes advantage of the way an image will maintain its proper aspect ratio when resized in an element. It tells whatever else is in video class element to take full-advantage of the real estate provided by the dynamic image by forcing its width/height to 100% of the video class element being adjusted by the image.

它的工作方式取决于视频类元素的位置属性和您想要的项保持一定的纵横比。它利用了图像在元素中调整大小时保持适当的纵横比的方法。它告诉视频类元素中的其他内容,通过强制将其宽度/高度设置为图像调整的视频类元素的100%,从而充分利用动态图像提供的房地产。

Pretty cool, eh?

很酷,不是吗?

You might have to play around with it a bit to get it to work with your own design, but this actually works surprisingly well for me. The general concept is there.

你可能需要花一点时间来让它和你自己的设计一起工作,但这实际上对我来说非常好。总的概念是这样的。

#4


13  

To add to Web_Designer's answer, the <div> will have a height (entirely made up of bottom padding) of 75% of the width of it's containing element. Here's a good summary: http://mattsnider.com/css-using-percent-for-margin-and-padding/. I'm not sure why this should be so, but that's how it is.

要补充Web_Designer的答案,

的高度(完全由底部填充组成)将是包含元素的宽度的75%。这里有一个很好的总结:http://mattsnider.com/css- use - % -for-margin-and-padding/。我不知道为什么会这样,但事实就是如此。

If you want your div to be a width other than 100%, you need another wrapping div on which to set the width:

如果您希望div的宽度大于100%,则需要另一个包装div来设置宽度:

div.ar-outer{
    width: 60%; /* container; whatever width you want */
    margin: 0 auto; /* centered if you like */
}
div.ar {
    width:100%; /* 100% of width of container */
    padding-bottom: 75%; /* 75% of width of container */
    position:relative;
}
div.ar-inner {
    position: absolute;
    top: 0; bottom: 0; left: 0; right: 0;
}

I used something similar to Elliot's image trick recently to allow me to use CSS media queries to serve a different logo file depending on device resolution, but still scale proportionally as an <img> would naturally do (I set the logo as background image to a transparent .png with the correct aspect ratio). But Web_Designer's solution would save me an http request.

我用类似艾略特的形象技巧最近允许我使用CSS媒体查询服务不同的标志文件根据设备分辨率,但仍然规模比例作为< img >自然会做(我设置标志背景图像与正确的长宽比)透明png。但是Web_Designer的解决方案将为我保存一个http请求。

#5


13  

Elliot inspired me to this solution - thanks:

埃利奥特启发我想到了这个解决方案——谢谢:

aspectratio.png is a completely transparent PNG-file with the size of your preferred aspect-ratio, in my case 30x10 pixels.

aspectratio。png是一个完全透明的pg -file,大小与您喜欢的方面比相同,在我的示例中是30x10像素。

HTML

<div class="eyecatcher">
  <img src="/img/aspectratio.png"/>
</div>

CSS3

.eyecatcher img {
  width: 100%;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-image: url(../img/autoresized-picture.jpg);
}

Please note: background-size is a css3-feature which might not work with your target-browsers. You may check interoperability (f.e. on caniuse.com).

请注意:background-size是一个css3特性,它可能不能与目标浏览器兼容。您可以在caniuse.com上检查互操作性(f.e.e)。

#6


9  

As stated in here on w3schools.com and somewhat reiterated in this accepted answer, padding values as percentages (emphasis mine):

正如w3schools.com网站上所述,并在这个公认的答案中有所重复,填充值作为百分比(强调我的):

Specifies the padding in percent of the width of the containing element

指定以包含元素宽度百分比表示的填充

Ergo, a correct example of a responsive DIV that keeps a 16:9 aspect ratio is as follows:

Ergo,一个响应性DIV保持16:9纵横比的正确示例如下:

CSS

CSS

.parent {
    position: relative;
    width: 100%;
}
.child {
    position: relative;
    padding-bottom: calc(100% * 9 / 16);
}
.child > div {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

HTML

HTML

<div class="parent">
    <div class="child">
        <div>Aspect is kept when resizing</div>
    </div>
</div>

Demo on JSFiddle

演示在JSFiddle

#7


9  

Basing on your solutions I've made some trick:

基于你的解决方案,我做了一些计谋:

When you use it, your HTML will be only

当您使用它时,您的HTML将是唯一的

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

To use it this way make: CSS:

要这样使用它,CSS:

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

and js (jQuery)

和js(jQuery)

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

And having this you just set attr data-keep-ratio to height/width and that's it.

有了这个,你只需要设置attr数据与高度/宽度的比值就可以了。

#8


6  

You can use an svg. Make the container/wrapper position relative, put the svg first as staticly positioned and then put absolutely positioned content (top: 0; left:0; right:0; bottom:0;)

您可以使用svg。使容器/包装器位置相对,首先将svg放置为静态位置,然后放置绝对位置的内容(顶部:0;左:0;右:0;底部:0,)

Example with 16:9 proportions:

示例与16:9比例:

image.svg: (can be inlined in src)

的形象。svg:(可以用src内联)

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 9" width="16" height="9"/>

CSS:

CSS:

.container {
  position: relative;
}
.content {
  position: absolute;
  top:0; left:0; right:0; bottom:0;
}

HTML:

HTML:

<div class="container">
  <img style="width: 100%" src="image.svg" />
  <div class="content"></div>
</div>

Note that inline svg doesn't seem to work, but you can urlencode the svg and embed it in img src attribute like this:

请注意,内嵌svg似乎并不起作用,但您可以将svg的代码uri编码,并将其嵌入到img src属性中:

<img src="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2016%209%22%20width%3D%2216%22%20height%3D%229%22%2F%3E" style="width: 100%;" />

#9


4  

As @web-tiki already show a way to use vh/vw, I also need a way to center in the screen, here is a snippet code for 9:16 portrait.

由于@web-tiki已经展示了一种使用vh/vw的方法,我还需要一种方法在屏幕中居中,这里是9:16竖屏的代码片段。

.container {
  width: 100vw;
  height: calc(100vw * 16 / 9);
  transform: translateY(calc((100vw * 16 / 9 - 100vh) / -2));
}

translateY will keep this center in the screen. calc(100vw * 16 / 9) is expected height for 9/16.(100vw * 16 / 9 - 100vh) is overflow height, so, pull up overflow height/2 will keep it center on screen.

翻译将把这个中心放在屏幕上。calc(100vw * 16 / 9)预计为9/16。(100vw * 16 / 9 - 100vh)为溢流高度,所以拉出溢流高度/2将保持在屏幕*。

For landscape, and keep 16:9, you show use

对于风景,保持16:9,你展示你的用途

.container {
  width: 100vw;
  height: calc(100vw * 9 / 16);
  transform: translateY(calc((100vw * 9 / 16 - 100vh) / -2));
}

The ratio 9/16 is ease to change, no need to predefined 100:56.25 or 100:75.If you want to ensure height first, you should switch width and height, e.g. height:100vh;width: calc(100vh * 9 / 16) for 9:16 portrait.

比率9/16易于更改,不需要预定义100:56.25或100:75。如果你想首先保证高度,你应该改变宽度和高度,比如高度:100vh;宽度:calc(100vh * 9 / 16)为9:16肖像。

If you want to adapted for different screen size, you may also interest

如果您想适应不同的屏幕大小,您可能也会感兴趣

  • background-size cover/contain
    • Above style is similar to contain, depends on width:height ratio.
    • 以上风格类似包含,依宽度:高比而定。
  • 背面尺寸的封面/上面的样式与上面的样式相似,取决于宽度:高比。
  • object-fit
    • cover/contain for img/video tag
    • 封面/包含img /视频标签
  • 对象适合的封面/包含img/视频标签
  • @media (orientation: portrait)/@media (orientation: landscape)
    • Media query for portrait/landscape to change the ratio.
    • 媒体查询为纵向/横向改变比例。
  • @media (orientation: portrait)/@media (orientation: landscape) Media query for portrait/landscape to change the ratio。

#10


3  

SCSS is the best solution in my case; using a data attribute :

SCSS是我的最佳解决方案;使用数据属性:

[data-aspect-ratio] {
    display: block;
    max-width: 100%;
    position: relative;

    &:before {
        content: '';
        display: block;
    }

    > * {
        display: block;
        height: 100%;
        left: 0;
        position: absolute;
        top: 0;
        width: 100%;
    }
}
[data-aspect-ratio="3:1"]:before {
    padding-top: 33.33%;
}
[data-aspect-ratio="2:1"]:before {
    padding-top: 50%;
}
[data-aspect-ratio="16:9"]:before {
    padding-top: 56.25%;
}
[data-aspect-ratio="3:2"]:before {
    padding-top: 66.66%;
}
[data-aspect-ratio="4:3"]:before {
    padding-top: 75%;
}
[data-aspect-ratio="1:1"]:before {
    padding-top: 100%;
}
[data-aspect-ratio="3:4"]:before {
    padding-top: 133.33%;
}
[data-aspect-ratio="2:3"]:before {
    padding-top: 150%;
}
[data-aspect-ratio="9:16"]:before {
    padding-top: 177.77%;
}
[data-aspect-ratio="1:2"]:before {
    padding-top: 200%;
}
[data-aspect-ratio="1:3"]:before {
    padding-top: 300%;
}

For example :

例如:

<div data-aspect-ratio="16:9"><iframe ...></iframe></div>

source

#11


2  

Just an idea or a hack.

只是一个想法或一个技巧。

div {
  background-color: blue;
  width: 10%;
  transition: background-color 0.5s, width 0.5s;
  font-size: 0;
}

div:hover {
  width: 20%;
  background-color: red;
}
  
img {
  width: 100%;
  height: auto;
  visibility: hidden;
}
<div>
  <!-- use an image with target aspect ratio. sample is a square -->
  <img src="http://i.imgur.com/9OPnZNk.png" />
</div>

#12


2  

lets say you have 2 divs the outher div is a container and the inner could be any element that you need to keep its ratio (img or an youtube iframe or whatever )

html looks like this :

html看起来是这样的:

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

lets say you need to keep the ratio of the "element"

假设你需要保持元素的比例

ratio => 4 to 1 or 2 to 1 ...

css looks like this

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 */
}

padding when specified in % it is calculated based on width not height. .. so basically you it doesn't matter what your width it height will always be calculated based of that . which will keep the ratio .

在%中指定的填充是根据宽度而不是高度计算的。所以基本上不管你的宽度是多少它的高度总是根据它来计算的。这个比值保持不变。

#13


2  

I have run into this issue quite some times, so I made a JS solution for it. This basically adjust the height of the domElement according the width of the element by the ratio you specify. You could use it as followed:

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

<div ratio="4x3"></div>

< div比率= " 4 x3 " > < / div >

Please be aware that since it is setting the height of the element, the element should be either a display:block or display:inline-block.

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

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

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

#14


1  

While most answers are very cool, most of them require to have an image already sized correctly... Other solutions only work for a width and do not care of the height available, but sometimes you want to fit the content in a certain height too.

虽然大多数答案都很酷,但大多数答案都要求图像大小正确……其他解决方案只适用于一个宽度,不关心可用的高度,但有时您也希望将内容适合于一个特定的高度。

I've tried to couple them together to bring a fully portable and re-sizable solution... The trick is to use to auto scaling of an image but use an inline svg element instead of using a pre-rendered image or any form of second HTTP request...

我试图将它们结合在一起,以带来一个完全可移植的、可重新调整大小的解决方案……诀窍是使用自动缩放图像,但使用内联svg元素,而不是使用预呈现的图像或任何形式的第二个HTTP请求……

div.holder{
  background-color:red;
  display:inline-block;
  height:100px;
  width:400px;
}
svg, img{
  background-color:blue;
  display:block;
  height:auto;
  width:auto;
  max-width:100%;
  max-height:100%;
}
.content_sizer{
  position:relative;
  display:inline-block;
  height:100%;
}
.content{
  position:absolute;
  top:0;
  bottom:0;
  left:0;
  right:0;
  background-color:rgba(155,255,0,0.5);
}
<div class="holder">
  <div class="content_sizer">
    <svg width=10000 height=5000 />
    <div class="content">
    </div>
  </div>
</div>

Notice that I have used big values in the width and height attributes of the SVG, as it needs to be bigger than the maximum expected size as it can only shrink. The example makes the div's ratio 10:5

请注意,我在SVG的宽度和高度属性中使用了大值,因为它需要大于最大预期大小,因为它只能收缩。这个示例使div的比例变为10:5

#15


1  

If you want to fit a square inside the viewport on either portrait or landscape view (as big as possible, but nothing sticking outside), switch between using vw/vh on orientation portrait/landscape:

如果你想在人像视图或景观视图中设置一个正方形(尽可能大,但不要在外面粘),在朝向肖像/景观中使用vw/vh:

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

#16


0  

You can use the flux layout (FWD).

您可以使用flux layout (FWD)。

https://en.wikipedia.org/wiki/Adaptive_web_design

https://en.wikipedia.org/wiki/Adaptive_web_design

It will scale and maintain the layout, its a bit complex but allows for a page to resize without pushing the content like (RWD).

它将扩展和维护布局,这有点复杂,但允许页面在不推送内容(RWD)的情况下调整大小。

It looks like responsive but it is scaling. https://www.youtube.com/watch?v=xRcBMLI4jbg

它看起来有响应性,但它正在扩展。https://www.youtube.com/watch?v=xRcBMLI4jbg

You can find the CSS scaling formula here:

你可以在这里找到CSS缩放公式:

http://plugnedit.com/pnew/928-2/

http://plugnedit.com/pnew/928-2/

#17


-1  

If the entire container structure was percentage based, this would be the default behavior, can you provide a more specific example?

如果整个容器结构是基于百分比的,这将是默认行为,您能提供一个更具体的示例吗?

Below is an example of what I mean, if your entire parent hierarchy was % based, any browser window adjustment would work without any additional js/css, is this not a possibility with your layout?

下面是一个例子,我的意思是,如果您的整个父层次结构是基于%的,那么任何浏览器窗口调整都可以在没有任何附加的js/css的情况下工作,这对您的布局来说不是可能的吗?

<div style="width: 100%;">
   <div style="width: 50%; margin: 0 auto;">Content</div>
</div>

#18


-1  

I used a new solution.

我用了一个新的解决方案。

.squares{
  width: 30vw
  height: 30vw

To main aspect ratio

主要方面比

.aspect-ratio
  width: 10vw
  height: 10vh

However, this is relative to the entire viewport. So, if you need a div that is 30% of the viewport width, you can use 30vw instead, and since you know the width, you reuse them in height using calc and vw unit.

但是,这是相对于整个viewport的。所以,如果你需要一个div,它是viewport宽度的30%,你可以使用30vw,因为你知道宽度,你可以用calc和vw单元来重复使用它们。

#1


1057  

Just create a wrapper <div> with a percentage value for padding-bottom, like this:

只需创建一个包装器

,其值为桨底的百分比值,如下所示:

div {
  width: 100%;
  padding-bottom: 75%;
  background: gold; /** <-- For the demo **/
}
<div></div>

It will result in a <div> with height equal to 75% of the width of its container (a 4:3 aspect ratio).

它将导致

,其高度等于其容器宽度的75%(4:3纵横比)。

This relies on the fact that for padding :

这依赖于如下事实:

The percentage is calculated with respect to the width of the generated box's containing block [...] (source: w3.org, emphasis mine)

这个百分比是根据生成的包含块的盒子的宽度来计算的。[来源:w3。org,强调我的)

Padding-bottom values for other aspect ratios and 100% width :

其他纵横比和100%宽度的划底值:

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

Placing content in the div :

在div中放置内容:

In order to keep the aspect ratio of the div and prevent its content from stretching it, you need to add an absolutely positioned child and stretch it to the edges of the wrapper with:

为了保持div的长宽比,防止其内容拉伸,需要添加一个绝对定位的子元素,将其拉伸到包装的边缘,如下所示:

div.stretchy-wrapper {
  position: relative;
}

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

Here's a demo and another more in depth demo

这是一个演示和另一个更深入的演示

#2


320  

vw units:

You can use vw units for both the width and height of the element. This allows the element's aspect ratio to be preserved, based on the viewport width.

你可以使用大众单位的宽度和高度的元素。这使得元素的纵横比得以保留,基于视窗宽度。

vw : 1/100th of the width of the viewport. [MDN]

大众:视场宽度的百分之一。(MDN)

Alternatively, you can also use vh for viewport height, or even vmin/vmax to use the lesser/greater of the viewport dimensions (discussion here).

或者,您也可以使用vh表示viewport高度,甚至vmin/vmax表示viewport维度的较小/较大(这里讨论)。

Example: 1:1 aspect ratio

div {
  width: 20vw;
  height: 20vw;
  background: gold;
}
<div></div>

For other aspect ratios, you can use the following table to calculate the value for height according to the width of the element :

对于其他纵横比,可以使用下表根据元素的宽度计算高度值:

aspect ratio  |  multiply width by
-----------------------------------
     1:1      |         1
     1:3      |         3
     4:3      |        0.75
    16:9      |       0.5625

Example: 4x4 grid of square divs

body {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
div {
  width: 23vw;
  height: 23vw;
  margin: 0.5vw auto;
  background: gold;
}
<div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>

Here is a Fiddle with this demo and here is a solution to make a responsive grid of squares with verticaly and horizontaly centered content.

这是演示的一部分,这是一个解决方案,用垂直和水平居中的内容创建一个响应性的正方形网格。


Browser support for vh/vw units is IE9+ see canIuse for more info

vh/vw部件的浏览器支持是IE9+,更多信息请参见canIuse

#3


25  

I've found a way to do this using CSS, but you have to be careful as it may change depending on the flow of your own web site. I've done it in order to embed video with a constant aspect ratio within a fluid width portion of my web site.

我已经找到了一种使用CSS的方法,但是你必须小心,因为它可能会根据你自己网站的流量而变化。我这样做是为了在我的网站的流体宽度部分嵌入具有恒定长宽比的视频。

Say you have an embedded video like this:

假设你有这样一个嵌入式视频:

<object>
     <param ... /><param ... />...
     <embed src="..." ...</embed>
</object>

You could then place this all inside a div with a "video" class. This video class will probably be the fluid element in your website such that, by itself, it has no direct height constraints, but when you resize the browser it will change in width according to the flow of the web site. This would be the element you are probably trying to get your embedded video in while maintaining a certain aspect ratio of the video.

然后,您可以将所有这些放在带有“video”类的div中。这个视频类很可能是你网站的流体元素,它本身没有直接的高度限制,但是当你调整浏览器的大小时,它会根据网站的流量变化。这可能是你想要嵌入视频的元素,同时保持视频的一定长宽比。

In order to do this, I put an image before the embedded object within the "video" class div.

为了做到这一点,我将一个图像放在“video”类div中嵌入的对象之前。

!!! The important part is that the image has the correct aspect ratio you wish to maintain. Also, make sure the size of the image is AT LEAST as big as the smallest you expect the video (or whatever you are maintaining the A.R. of) to get based on your layout. This will avoid any potential issues in the resolution of the image when it is percentage-resized. For example, if you wanted to maintain an aspect ratio of 3:2, don't just use a 3px by 2px image. It may work under some circumstances, but I haven't tested it, and it would probably be a good idea to avoid.

! ! !重要的是图像有你希望维护的正确的纵横比。此外,确保图像的大小至少与您希望视频(或任何您正在维护的内容)根据布局得到的最小大小一样大。这将避免在调整百分比大小时在图像分辨率中出现的任何潜在问题。例如,如果你想保持3:2的长宽比,不要只使用3px * 2px的图像。它可能在某些情况下有效,但我还没有测试过它,所以最好避免它。

You should probably already have a minimum width like this defined for fluid elements of your web site. If not, it is a good idea to do so in order to avoid chopping elements off or having overlap when the browser window gets too small. It is better to have a scroll bar at some point. The smallest in width a web page should get is somewhere around ~600px (including any fixed width columns) because screen resolutions don't come smaller unless you are dealing with phone-friendly sites. !!!

您可能已经为web站点的流体元素定义了这样的最小宽度。如果不是,那么最好这样做,以避免在浏览器窗口太小时将元素截断或重叠。最好在某个点设置一个滚动条。一个网页的最小宽度应该在600像素左右(包括任何固定宽度的列),因为屏幕分辨率不会变小,除非你是在处理手机友好的网站。! ! !

I use a completely transparent png but I don't really think it ends up mattering if you do it right. Like this:

我使用的是完全透明的png,但我认为如果你做得对,它最终并不重要。是这样的:

<div class="video">
     <img class="maintainaspectratio" src="maintainaspectratio.png" />
     <object>
          <param ... /><param ... />...
          <embed src="..." ...</embed>
     </object>
</div>

Now you should be able to add CSS similar to the following:

现在您应该能够添加类似以下的CSS:

div.video { ...; position: relative; }
div.video img.maintainaspectratio { width: 100%; }
div.video object { position: absolute; top: 0px; left: 0px; width: 100%; height: 100%; }
div.video embed {width: 100%; height: 100%; }

Make sure you also remove any explicit height or width declaration within the object and embed tags that usually come with copy/pasted embed code.

确保您还删除了对象中的任何显式高度或宽度声明,并嵌入通常带有复制/粘贴嵌入代码的标记。

The way it works depends on the position properties of the video class element and the item you want have maintain a certain aspect ratio. It takes advantage of the way an image will maintain its proper aspect ratio when resized in an element. It tells whatever else is in video class element to take full-advantage of the real estate provided by the dynamic image by forcing its width/height to 100% of the video class element being adjusted by the image.

它的工作方式取决于视频类元素的位置属性和您想要的项保持一定的纵横比。它利用了图像在元素中调整大小时保持适当的纵横比的方法。它告诉视频类元素中的其他内容,通过强制将其宽度/高度设置为图像调整的视频类元素的100%,从而充分利用动态图像提供的房地产。

Pretty cool, eh?

很酷,不是吗?

You might have to play around with it a bit to get it to work with your own design, but this actually works surprisingly well for me. The general concept is there.

你可能需要花一点时间来让它和你自己的设计一起工作,但这实际上对我来说非常好。总的概念是这样的。

#4


13  

To add to Web_Designer's answer, the <div> will have a height (entirely made up of bottom padding) of 75% of the width of it's containing element. Here's a good summary: http://mattsnider.com/css-using-percent-for-margin-and-padding/. I'm not sure why this should be so, but that's how it is.

要补充Web_Designer的答案,

的高度(完全由底部填充组成)将是包含元素的宽度的75%。这里有一个很好的总结:http://mattsnider.com/css- use - % -for-margin-and-padding/。我不知道为什么会这样,但事实就是如此。

If you want your div to be a width other than 100%, you need another wrapping div on which to set the width:

如果您希望div的宽度大于100%,则需要另一个包装div来设置宽度:

div.ar-outer{
    width: 60%; /* container; whatever width you want */
    margin: 0 auto; /* centered if you like */
}
div.ar {
    width:100%; /* 100% of width of container */
    padding-bottom: 75%; /* 75% of width of container */
    position:relative;
}
div.ar-inner {
    position: absolute;
    top: 0; bottom: 0; left: 0; right: 0;
}

I used something similar to Elliot's image trick recently to allow me to use CSS media queries to serve a different logo file depending on device resolution, but still scale proportionally as an <img> would naturally do (I set the logo as background image to a transparent .png with the correct aspect ratio). But Web_Designer's solution would save me an http request.

我用类似艾略特的形象技巧最近允许我使用CSS媒体查询服务不同的标志文件根据设备分辨率,但仍然规模比例作为< img >自然会做(我设置标志背景图像与正确的长宽比)透明png。但是Web_Designer的解决方案将为我保存一个http请求。

#5


13  

Elliot inspired me to this solution - thanks:

埃利奥特启发我想到了这个解决方案——谢谢:

aspectratio.png is a completely transparent PNG-file with the size of your preferred aspect-ratio, in my case 30x10 pixels.

aspectratio。png是一个完全透明的pg -file,大小与您喜欢的方面比相同,在我的示例中是30x10像素。

HTML

<div class="eyecatcher">
  <img src="/img/aspectratio.png"/>
</div>

CSS3

.eyecatcher img {
  width: 100%;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-image: url(../img/autoresized-picture.jpg);
}

Please note: background-size is a css3-feature which might not work with your target-browsers. You may check interoperability (f.e. on caniuse.com).

请注意:background-size是一个css3特性,它可能不能与目标浏览器兼容。您可以在caniuse.com上检查互操作性(f.e.e)。

#6


9  

As stated in here on w3schools.com and somewhat reiterated in this accepted answer, padding values as percentages (emphasis mine):

正如w3schools.com网站上所述,并在这个公认的答案中有所重复,填充值作为百分比(强调我的):

Specifies the padding in percent of the width of the containing element

指定以包含元素宽度百分比表示的填充

Ergo, a correct example of a responsive DIV that keeps a 16:9 aspect ratio is as follows:

Ergo,一个响应性DIV保持16:9纵横比的正确示例如下:

CSS

CSS

.parent {
    position: relative;
    width: 100%;
}
.child {
    position: relative;
    padding-bottom: calc(100% * 9 / 16);
}
.child > div {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

HTML

HTML

<div class="parent">
    <div class="child">
        <div>Aspect is kept when resizing</div>
    </div>
</div>

Demo on JSFiddle

演示在JSFiddle

#7


9  

Basing on your solutions I've made some trick:

基于你的解决方案,我做了一些计谋:

When you use it, your HTML will be only

当您使用它时,您的HTML将是唯一的

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

To use it this way make: CSS:

要这样使用它,CSS:

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

and js (jQuery)

和js(jQuery)

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

And having this you just set attr data-keep-ratio to height/width and that's it.

有了这个,你只需要设置attr数据与高度/宽度的比值就可以了。

#8


6  

You can use an svg. Make the container/wrapper position relative, put the svg first as staticly positioned and then put absolutely positioned content (top: 0; left:0; right:0; bottom:0;)

您可以使用svg。使容器/包装器位置相对,首先将svg放置为静态位置,然后放置绝对位置的内容(顶部:0;左:0;右:0;底部:0,)

Example with 16:9 proportions:

示例与16:9比例:

image.svg: (can be inlined in src)

的形象。svg:(可以用src内联)

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 9" width="16" height="9"/>

CSS:

CSS:

.container {
  position: relative;
}
.content {
  position: absolute;
  top:0; left:0; right:0; bottom:0;
}

HTML:

HTML:

<div class="container">
  <img style="width: 100%" src="image.svg" />
  <div class="content"></div>
</div>

Note that inline svg doesn't seem to work, but you can urlencode the svg and embed it in img src attribute like this:

请注意,内嵌svg似乎并不起作用,但您可以将svg的代码uri编码,并将其嵌入到img src属性中:

<img src="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2016%209%22%20width%3D%2216%22%20height%3D%229%22%2F%3E" style="width: 100%;" />

#9


4  

As @web-tiki already show a way to use vh/vw, I also need a way to center in the screen, here is a snippet code for 9:16 portrait.

由于@web-tiki已经展示了一种使用vh/vw的方法,我还需要一种方法在屏幕中居中,这里是9:16竖屏的代码片段。

.container {
  width: 100vw;
  height: calc(100vw * 16 / 9);
  transform: translateY(calc((100vw * 16 / 9 - 100vh) / -2));
}

translateY will keep this center in the screen. calc(100vw * 16 / 9) is expected height for 9/16.(100vw * 16 / 9 - 100vh) is overflow height, so, pull up overflow height/2 will keep it center on screen.

翻译将把这个中心放在屏幕上。calc(100vw * 16 / 9)预计为9/16。(100vw * 16 / 9 - 100vh)为溢流高度,所以拉出溢流高度/2将保持在屏幕*。

For landscape, and keep 16:9, you show use

对于风景,保持16:9,你展示你的用途

.container {
  width: 100vw;
  height: calc(100vw * 9 / 16);
  transform: translateY(calc((100vw * 9 / 16 - 100vh) / -2));
}

The ratio 9/16 is ease to change, no need to predefined 100:56.25 or 100:75.If you want to ensure height first, you should switch width and height, e.g. height:100vh;width: calc(100vh * 9 / 16) for 9:16 portrait.

比率9/16易于更改,不需要预定义100:56.25或100:75。如果你想首先保证高度,你应该改变宽度和高度,比如高度:100vh;宽度:calc(100vh * 9 / 16)为9:16肖像。

If you want to adapted for different screen size, you may also interest

如果您想适应不同的屏幕大小,您可能也会感兴趣

  • background-size cover/contain
    • Above style is similar to contain, depends on width:height ratio.
    • 以上风格类似包含,依宽度:高比而定。
  • 背面尺寸的封面/上面的样式与上面的样式相似,取决于宽度:高比。
  • object-fit
    • cover/contain for img/video tag
    • 封面/包含img /视频标签
  • 对象适合的封面/包含img/视频标签
  • @media (orientation: portrait)/@media (orientation: landscape)
    • Media query for portrait/landscape to change the ratio.
    • 媒体查询为纵向/横向改变比例。
  • @media (orientation: portrait)/@media (orientation: landscape) Media query for portrait/landscape to change the ratio。

#10


3  

SCSS is the best solution in my case; using a data attribute :

SCSS是我的最佳解决方案;使用数据属性:

[data-aspect-ratio] {
    display: block;
    max-width: 100%;
    position: relative;

    &:before {
        content: '';
        display: block;
    }

    > * {
        display: block;
        height: 100%;
        left: 0;
        position: absolute;
        top: 0;
        width: 100%;
    }
}
[data-aspect-ratio="3:1"]:before {
    padding-top: 33.33%;
}
[data-aspect-ratio="2:1"]:before {
    padding-top: 50%;
}
[data-aspect-ratio="16:9"]:before {
    padding-top: 56.25%;
}
[data-aspect-ratio="3:2"]:before {
    padding-top: 66.66%;
}
[data-aspect-ratio="4:3"]:before {
    padding-top: 75%;
}
[data-aspect-ratio="1:1"]:before {
    padding-top: 100%;
}
[data-aspect-ratio="3:4"]:before {
    padding-top: 133.33%;
}
[data-aspect-ratio="2:3"]:before {
    padding-top: 150%;
}
[data-aspect-ratio="9:16"]:before {
    padding-top: 177.77%;
}
[data-aspect-ratio="1:2"]:before {
    padding-top: 200%;
}
[data-aspect-ratio="1:3"]:before {
    padding-top: 300%;
}

For example :

例如:

<div data-aspect-ratio="16:9"><iframe ...></iframe></div>

source

#11


2  

Just an idea or a hack.

只是一个想法或一个技巧。

div {
  background-color: blue;
  width: 10%;
  transition: background-color 0.5s, width 0.5s;
  font-size: 0;
}

div:hover {
  width: 20%;
  background-color: red;
}
  
img {
  width: 100%;
  height: auto;
  visibility: hidden;
}
<div>
  <!-- use an image with target aspect ratio. sample is a square -->
  <img src="http://i.imgur.com/9OPnZNk.png" />
</div>

#12


2  

lets say you have 2 divs the outher div is a container and the inner could be any element that you need to keep its ratio (img or an youtube iframe or whatever )

html looks like this :

html看起来是这样的:

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

lets say you need to keep the ratio of the "element"

假设你需要保持元素的比例

ratio => 4 to 1 or 2 to 1 ...

css looks like this

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 */
}

padding when specified in % it is calculated based on width not height. .. so basically you it doesn't matter what your width it height will always be calculated based of that . which will keep the ratio .

在%中指定的填充是根据宽度而不是高度计算的。所以基本上不管你的宽度是多少它的高度总是根据它来计算的。这个比值保持不变。

#13


2  

I have run into this issue quite some times, so I made a JS solution for it. This basically adjust the height of the domElement according the width of the element by the ratio you specify. You could use it as followed:

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

<div ratio="4x3"></div>

< div比率= " 4 x3 " > < / div >

Please be aware that since it is setting the height of the element, the element should be either a display:block or display:inline-block.

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

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

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

#14


1  

While most answers are very cool, most of them require to have an image already sized correctly... Other solutions only work for a width and do not care of the height available, but sometimes you want to fit the content in a certain height too.

虽然大多数答案都很酷,但大多数答案都要求图像大小正确……其他解决方案只适用于一个宽度,不关心可用的高度,但有时您也希望将内容适合于一个特定的高度。

I've tried to couple them together to bring a fully portable and re-sizable solution... The trick is to use to auto scaling of an image but use an inline svg element instead of using a pre-rendered image or any form of second HTTP request...

我试图将它们结合在一起,以带来一个完全可移植的、可重新调整大小的解决方案……诀窍是使用自动缩放图像,但使用内联svg元素,而不是使用预呈现的图像或任何形式的第二个HTTP请求……

div.holder{
  background-color:red;
  display:inline-block;
  height:100px;
  width:400px;
}
svg, img{
  background-color:blue;
  display:block;
  height:auto;
  width:auto;
  max-width:100%;
  max-height:100%;
}
.content_sizer{
  position:relative;
  display:inline-block;
  height:100%;
}
.content{
  position:absolute;
  top:0;
  bottom:0;
  left:0;
  right:0;
  background-color:rgba(155,255,0,0.5);
}
<div class="holder">
  <div class="content_sizer">
    <svg width=10000 height=5000 />
    <div class="content">
    </div>
  </div>
</div>

Notice that I have used big values in the width and height attributes of the SVG, as it needs to be bigger than the maximum expected size as it can only shrink. The example makes the div's ratio 10:5

请注意,我在SVG的宽度和高度属性中使用了大值,因为它需要大于最大预期大小,因为它只能收缩。这个示例使div的比例变为10:5

#15


1  

If you want to fit a square inside the viewport on either portrait or landscape view (as big as possible, but nothing sticking outside), switch between using vw/vh on orientation portrait/landscape:

如果你想在人像视图或景观视图中设置一个正方形(尽可能大,但不要在外面粘),在朝向肖像/景观中使用vw/vh:

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

#16


0  

You can use the flux layout (FWD).

您可以使用flux layout (FWD)。

https://en.wikipedia.org/wiki/Adaptive_web_design

https://en.wikipedia.org/wiki/Adaptive_web_design

It will scale and maintain the layout, its a bit complex but allows for a page to resize without pushing the content like (RWD).

它将扩展和维护布局,这有点复杂,但允许页面在不推送内容(RWD)的情况下调整大小。

It looks like responsive but it is scaling. https://www.youtube.com/watch?v=xRcBMLI4jbg

它看起来有响应性,但它正在扩展。https://www.youtube.com/watch?v=xRcBMLI4jbg

You can find the CSS scaling formula here:

你可以在这里找到CSS缩放公式:

http://plugnedit.com/pnew/928-2/

http://plugnedit.com/pnew/928-2/

#17


-1  

If the entire container structure was percentage based, this would be the default behavior, can you provide a more specific example?

如果整个容器结构是基于百分比的,这将是默认行为,您能提供一个更具体的示例吗?

Below is an example of what I mean, if your entire parent hierarchy was % based, any browser window adjustment would work without any additional js/css, is this not a possibility with your layout?

下面是一个例子,我的意思是,如果您的整个父层次结构是基于%的,那么任何浏览器窗口调整都可以在没有任何附加的js/css的情况下工作,这对您的布局来说不是可能的吗?

<div style="width: 100%;">
   <div style="width: 50%; margin: 0 auto;">Content</div>
</div>

#18


-1  

I used a new solution.

我用了一个新的解决方案。

.squares{
  width: 30vw
  height: 30vw

To main aspect ratio

主要方面比

.aspect-ratio
  width: 10vw
  height: 10vh

However, this is relative to the entire viewport. So, if you need a div that is 30% of the viewport width, you can use 30vw instead, and since you know the width, you reuse them in height using calc and vw unit.

但是,这是相对于整个viewport的。所以,如果你需要一个div,它是viewport宽度的30%,你可以使用30vw,因为你知道宽度,你可以用calc和vw单元来重复使用它们。