I have been trying to make an image slider that would fit into a side bar in my website im building, however, its been coming out with different pictures with different aspect ratios making it look all messy. I want to try having it where it will automatically crop (maybe even round it) with my current slider I'm using. Thanks in advance!
<head>
<style type="text/css">
#slider {
overflow: hidden;
}
#slider figure {
position: relative;
width: 500%;
margin: 0;
left: 0;
animation: 20s slider infinite;
}
#slider figure img {
float: left;
width: 20%;
}
@keyframes slider {
0% {
left: 0;
}
20% {
left: 0;
}
25% {
left: -100%;
}
45% {
left: -100%;
}
50% {
left: -200%;
}
70% {
left: -200%;
}
75% {
left: -300%;
}
95% {
left: -300%;
}
100% {
left: -400%;
}
}
</style>
</head>
<body>
<div id="slider">
<figure>
<img src="img/plant.png">
<img src="img/plant2.png">
<img src="img/plant3.png">
<img src="img/plant4.png">
<img src="img/plant.png">
</figure>
</div>
</body>
</html>
CodePudding user response:
The trick is to force all images to inherit the height of the parent element by min-height: 100%;
and height: auto;
and then use object-fit: cover;
to keep the aspect ratio.
#slider {
overflow: hidden;
height: 180px; /* or any value depending on how high you want it to be. 100% for matching the longest image */
}
#slider figure {
display: flex;
width: 500%;
height: 100%;
margin: 0;
position: relative;
animation: 20s slider infinite;
}
#slider figure img {
display: block;
width: 20%;
min-height: 100%;
object-fit: cover;
height: auto;
}
@keyframes slider {
0% {
left: 0;
}
20% {
left: 0;
}
25% {
left: -100%;
}
45% {
left: -100%;
}
50% {
left: -200%;
}
70% {
left: -200%;
}
75% {
left: -300%;
}
95% {
left: -300%;
}
100% {
left: -400%;
}
}
<div id="slider">
<figure>
<img src="http://placekitten.com/700/300">
<img src="http://placekitten.com/600/600">
<img src="http://placekitten.com/500/300">
<img src="http://placekitten.com/700/400">
<img src="http://placekitten.com/700/300">
</figure>
</div>
and one more thing, position: relative;
does not take left
, right
, ... values. That works only on absolute
and fix
positioned elements.