我正在寻找一种纯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();
})
});
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;
}
<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>
这是一个演示我拥有的笔的网页。 https://codepen.io/nom3d/pen/arGpBV
这是一个动态图展示缩放时的效果。请注意背景图片保持比例,文本保持居中对齐。
如果只用 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);
};
height: calc((1000px / 3) * .75)
的公式,利用calc
函数为footer
设置高度,但是当你调整窗口大小时它无法起到作用,只有使用 JS 才能捕获调整大小事件并计算每个像素的高度比例来设置高度。 - Towkir1000px
。 - The24thDSCSS
的解决方案是添加5行代码,可以给你想要的宽高比。 - user2560539calc
,这不会使它成为纯CSS
解决方案吗?@Towkir - user2560539calc
是一个纯 CSS 解决方案。 - Towkir