根据宽度计算div的高度并保持比例

dro*_*ooh 12 html javascript css height responsive

我正在寻找一种纯CSS解决方案,以解决我在这里使用jQuery所提供的帮助。

基本上,我有3个div,它们在容器中的宽度均匀分布。它们保持3/4的比例,高度是根据宽度计算得出的。此外,每个div都有一个与背景成比例的背景图像以及一些水平和垂直居中的文本。

$(document).ready(function() {
  function setw() {
    var footdivwidth = $('footer div').width();
    var footdivheight = footdivwidth * .75;
    $('footer div').css({
      'height': footdivheight + 'px'
    });
    $('footer div span').html('w: ' + footdivwidth + '<br>h: ' + footdivheight);
  }
  setw();
  $(window).resize(function() {
    setw();
  })
});
Run Code Online (Sandbox Code Playgroud)
FOOTER {
  max-width: 1000px;
  margin: 0 auto;
  background-color: rgba(0, 0, 0, 0.171);
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

FOOTER DIV {
  background-image: url('https://learnwebdesign.online/img/bg.jpg');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  flex: 1;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

FOOTER DIV SPAN {
  display: inline-block;
  text-align: center;
  background-color: rgba(165, 165, 165, 0.282);
  padding: 7px 15px;
  border-radius: 3px;
  color: #FFFFFF;
  text-transform: uppercase;
  font-weight: bold;
  letter-spacing: 2px;
  font-size: 21px;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<footer>
  <div><span>left photo</span></div>
  <div><span>center photo</span></div>
  <div><span>right photo and more text</span></div>
</footer>
Run Code Online (Sandbox Code Playgroud)

这是一支笔,显示我所拥有的。 https://codepen.io/nom3d/pen/arGpBV

这是显示调整大小后的效果的gif。请注意背景图像保持比例,文本保持居中。 3盒调整大小并保持比例

还想知道如果仅CSS不可能做到这一点,如何使用普通javascript做到这一点,我是否需要在div中添加id?

更新:这是一个简单的javaScript函数来处理此任务

function setHeight(el,val){
    var box = document.querySelectorAll(el);
    var i;
    for(i = 0;i < box.length;i++){
        var width = box[i].offsetWidth;
        var height = width * val;
        box[i].style.height = height + 'px';        
    }
}
// set your element to target and the ratio value
setHeight('footer div',.75);
window.onresize = function(event) {
    setHeight('footer div',.75);
};
Run Code Online (Sandbox Code Playgroud)

小智 0

你有没有尝试过

footer div {
    height: 20vw;
}
Run Code Online (Sandbox Code Playgroud)

css 还有 calc 属性,这可能会有所帮助

https://developer.mozilla.org/en-US/docs/Web/CSS/calc