如何在保持宽高比的同时使用CSS自动调整DIV大小?

Aar*_*ron 7 html css php forms autoresize

我所拥有的是HTML中的标准表单,允许用户选择"宽度"选项和"高度"选项(每个选项的值范围为1到10).当他们发送表单时,它会将其发送到PHP/HTML页面,其中PHP抓取"宽度"和"高度"变量并将其分配给DIV的宽度和高度.

但我想要做的只是使用"宽度"和"高度"变量为该DIV指定宽高比,然后将该DIV自动调整为其内部容器的100%,但同时保持相同的宽高比.

示例: 用户选择宽度4和高度2,然后发送表单.在接收PHP页面上,DIV(接收宽度和高度比率的那个)位于容量为1000px宽度和600px高度的容器内.所以现在,DIV调整到1000px宽和500px高(这将是4到2的宽高比)

任何想法,代码,脚本都会非常有用,非常感谢!

亚伦

Ori*_*iol 7

由于padding-*属性的百分比值是根据生成的框的包含块的宽度计算的,因此您可以:

  • 添加一个没有内容但在垂直填充(padding-toppadding-bottom)中具有百分比的虚拟元素,对应于所需的宽高比.
  • 使用绝对定位从元件的正常流动中移除所有内容,以防止它们增加高度.然后,让它长大以填充容器.

这个想法来自http://ansciath.tumblr.com/post/7347495869/css-aspect-ratio

#container {
  position: relative;
  width: 50%;
}
#dummy {
  padding-top: 75%; /* 4:3 aspect ratio */
}
#element {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: silver;
}
Run Code Online (Sandbox Code Playgroud)
<div id="container">
  <div id="dummy"></div>
  <div id="element">
    some text
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

注意可以使用垂直边距而不是垂直填充,但随后会出现边距崩溃.要防止它,请添加

#container {
  display: inline-block;
}
Run Code Online (Sandbox Code Playgroud)

#container {
  display: inline-block;
  position: relative;
  width: 50%;
}
#dummy {
  margin-top: 75%; /* 4:3 aspect ratio */
}
#element {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: silver;
}
Run Code Online (Sandbox Code Playgroud)
<div id="container">
  <div id="dummy"></div>
  <div id="element">
    some text
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

使用::before伪元素,不需要使用虚拟元素:

#container:before {
  padding-top: 75%; /* 4:3 aspect ratio */
  content: ''; /* Enable the pseudo-element */
  display: block;    
}
Run Code Online (Sandbox Code Playgroud)

#container {
  position: relative;
  width: 50%;
}
#container:before {
  padding-top: 75%; /* 4:3 aspect ratio */
  content: ''; /* Enable the pseudo-element */
  display: block;    
}
#element {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: silver;
}
Run Code Online (Sandbox Code Playgroud)
<div id="container">
  <div id="element">
    some text
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)