html - 动态强制 div 的宽度等于其高度

标签 html css

在这里,我试图使 div 的宽度与其高度完全相同,以使其保持完美的正方形。高度是其父 div 的百分比,因此没有其高度的精确像素值。

如果我不知道确切的像素高度,如何使 div 完全正方形?

我在下面给出了一个链接来演示我所说的内容。在示例中,我希望青色 div 动态转换其宽度以匹配其高度尺寸,从而使其保持完美的正方形。我希望能够在 CSS 代码中做到这一点,但如果不能,也没关系。

https://jsfiddle.net/5pdLpqrg/

CSS:

#parent{
  height: 70px;
  width: 450px;
  background: #999;
  resize: both;
  overflow: auto;
}
#perfect_square{
  height: 78%;
  width: 80px;
  background: cyan;
}

最佳答案

这是一个仅 CSS 解决方案:

#parent {
  width:350px;
  height:200px;
  background:silver; 
}

#container {
    display: inline-block;
    position: relative;
    width: 50%;
}
#container:after {
    content: '';
    display: block;
    margin-top: 100%;
}
#perfect_square {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: cyan;
}
<div id="parent">
  <div id="container">
      <div id="dummy"></div>
      <div id="perfect_square">
      </div>
  </div>
</div>

另一个仅 CSS 解决方案:

.parent {
  width:600px;
  height:500px;
  background:silver;
}

.perfect_square {
    width: 20%;
    height: 0;
    padding-bottom: 20%;
    background:cyan;
}
<div class="parent">
  <div class="perfect_square"></div>
</div>

希望有帮助!

关于html - 动态强制 div 的宽度等于其高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34669951/

相关文章:

html - 响应式数据表

html - 列表项之间不需要的边距或填充

css - 在 React 组件中使用 css/scss 变量作为内联样式

html - Twitter bootstrap 下拉事件导航创建一个白色区域并且看起来很奇怪

javascript - 在键入 bootstrap select jquery 时加载选择选项

html - 在 Chrome 扩展中使用 localStorage 或 chrome.storage 的安全问题

javascript - 如何启动 IMA HTML5 SDK 广告静音?

css - Internet Explorer 8 中的字体问题

php - 如何获取链接标签的href内容

html - 如何在 Chrome 中调整纯 flexbox masonry 网格,它已经在 Firefox 中运行