我有一张图片幻灯片。它由几个部分组成:
这些图像彼此叠放,在“前”,“中”和“后”的角色之间相互转换。“中间”图像的不透明度为1,其他图像的不透明度为0。每隔几秒钟,一个Javascript函数会将当前的“背面”图像指定为新的“中间”图像,并将“中间”图像指定为新的“正面”图像,从而更改其相应的不透明性(接下来的一秒钟CSS过渡结束,彼此淡入淡出)。原来位于“前”的图像将被放弃,并将新图像加载到“后”(通过src
直接更改属性)。
我希望这些图像能填充它们可用的整个屏幕空间(底部栏除外),同时保持其纵横比。图像尺寸的下限是哪个尺寸决定了图像的尺寸。同时,图像需要以未填充的任何尺寸居中(因此,对于高图像,应水平居中,对于宽图像,应垂直居中)。此外,图像需要适应不断变化的屏幕尺寸,最好是拖动窗口尺寸时。
我当前正在使用一个冗长的Javascript函数来(1)通过从屏幕高度中减去底部栏的高度来找到可用空间,(2)计算图像的长宽比,(3)比较哪个尺寸是极限因素,以及(4)相应地调整元素的大小和位置。该函数由window.onresize
事件触发,并在图像更改时手动触发。但是,单击并拖动以更改窗口大小时,该函数会反复调用。这是不必要的计算密集型操作,如果可能的话,我想在CSS中更改大小。
当我遇到通常显示图像的网站的问题时,我的解决方案是calc()
:
img.class {
font-size:24pt; /* same font size as h1, which is the biggest title element. Used to calculate em */
max-width: calc(100vw - 80px); /* exactly enough to account for horizontal margins/padding */
max-height: calc(100vh - 2em); /* leave space for title but otherwise fill window */
}
两者之间的区别在于,唯一的限制因素是屏幕尺寸,而我确切知道“应该”适合屏幕显示的其他元素的大小。整个父元素都居中(当然,水平居中很容易),而且由于屏幕应该滚动,所以我完全不必担心垂直居中。因此,我认为这种解决方案在这里不可重用。
我尝试了直观的解决方案是把水平和垂直对齐的父母<div>
,并设置max-width
和max-height
百分比(因为我不能得到不同元素的高度在CSS中做数学含)的条款:
#parent{
width: 100%;
height: 100%;
top: 0;
left: 0;
position: relative;
padding: 0;
margin: 0;
}
img {
transition: opacity 1s;
margin: auto;
max-width: 100%;
max-height: 100%;
}
但是,这不仅没有使图像居中,而且使它们根本不显示!从中移出max-width
和max-height
移出<img>
图像会使图像出现,但溢出屏幕的侧面和下面的导航栏,这也不是我想要的。如何使用CSS而不是冗长的JavaScript正确完成此任务?
我认为这种布局结构可以满足您的所有要求。在这里,我将不透明性降低了三幅大小不一的图像,因此您可以看到它们如何一起缩放。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
margin: 0;
}
.images {
position: relative;
height: 100%;
}
.image {
position: absolute;
background-size: contain;
background-repeat: no-repeat;
background-position: center center;
width: 100%;
height: 100%;
opacity: 0.5;
}
.image-container {
position: relative;
width: 100%;
height: 100%;
}
.container {
display: flex;
flex-direction: column;
height: 100vh;
}
.footer {
background-color: black;
color: white;
height: 50px;
width: 100%;
margin-top: auto;
}
</style>
</head>
<body>
<div class="container">
<div class="images">
<div class="image-container">
<div class="image" style="background-image: url(https://unsplash.it/1000/425)"></div>
<div class="image" style="background-image: url(https://unsplash.it/640/1000)"></div>
<div class="image" style="background-image: url(https://unsplash.it/800/800)"></div>
</div>
</div>
<div class="footer">Content</div>
</div>
</body>
</html>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句