【发布时间】:2020-04-11 00:20:23
【问题描述】:
我正在编写一个简单的英雄部分,每 2 秒自动更改背景中的图像。但是,由于图像具有不同的尺寸,因此它们在更大的屏幕上看起来确实被压扁了。如何解决此问题并使其响应并适应各种屏幕尺寸?
$hero: 100vh;
$white: #fff;
$black: #000;
$blue: #6db8d7;
$grey: #808080;
* {
box-sizing: border-box;
}
body {
padding: 0;
margin: 0;
}
.hero-body {
height: 100vh;
width: 100vw;
position: relative;
overflow: hidden;
text-align: center;
}
.hero-text {
position: absolute;
bottom: 40%;
left: 20px;
}
img {
width: 100%;
height: $hero;
}
.title,
h4 {
color: $white;
font-size: 1em;
text-shadow: 1px 1px 2px $black;
text-align: center;
}
button {
background-color: $blue;
padding: 10px;
text-transform: uppercase;
font-weight: 500;
color: $white;
text-align: center;
border: 1px solid transparent;
border-radius: 6px;
box-shadow: 0 3px 6px 0 $grey;
cursor: pointer;
&:hover,
&:focus {
transform: scale(1.05);
transition: all 0.5s ease-in-out;
}
}
<section class="hero">
<div class="hero-body">
<img class="bg-img" src="https://source.unsplash.com/alEZLDPPRBU">
<img class="bg-img" src="https://source.unsplash.com/Ov0u44CyGdM">
<img class="bg-img" src="https://source.unsplash.com/8beTH4VkhLI">
<div class="hero-text">
<h1 class="title">
Delight, Fresh, Fruity
</h1>
<h4>Come join us for our organic cones!</h4>
<button>View flavors</button>
</div>
</div>
</section>
【问题讨论】:
-
如果只针对现代浏览器,您可以覆盖容器:
img { width: 100%; height: 100%; object-fit: cover;(其工作方式与background-size: cover;类似),但您可能希望将文本设为静态,并且而是将图像设为position: absolute;。 -
谢谢!这完美地工作。 @chriskirknielsen