Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use background images with owl carousel

I'd like to use owl carousel with background images rather than <img> tags, like used in http://driveshift.com/car/c10148. However, every example included in the plugin site uses the img tags.

When you inspect the Shift carousel, it uses url images as data-src attributes and then owl carousel auto converts them to background images. Any suggestions?

like image 585
Salman Ahmed Avatar asked Jun 05 '15 11:06

Salman Ahmed


2 Answers

Check out the example code at https://owlcarousel2.github.io/OwlCarousel2/demos/lazyLoad.html

LazyLoad HTML strucutre requires class="owl-lazy" and data-src="url_to_img" or/and data-src-retina="url_to_highres_img". If you set above settings not on but on other DOM element then Owl will load an image into css inline background style.

Therefore, if you use <div> instead of <img>, you'll get your desired result.

<div class="owl-lazy" data-src="http://placehold.it/350x250&text=3">

Note that you may need to add some CSS to the div for it to look correctly. Hope that helps!

like image 168
paulshen Avatar answered Sep 28 '22 12:09

paulshen


I was somewhat looking for a similar solution to your question and following the solution proposed by Paulshen I had it working. Basically I created my carousel elements with div and set the data src to the image url pulled from the database and then manipulated it with css and media queries to get it working correctly as he suggested.

Hope this helps, find below:

HTML:

<div class="owl-carousel owl-theme">
<div class="slide-item owl-lazy" data-src="https://placehold.it/350x250&text=3"></div>
<div class="slide-item owl-lazy" data-src="https://placehold.it/350x250&text=3"></div>
</div>

CSS:

.slide-item{ position: relative;
background-repeat: no-   repeat;
background-position: top center;background-size: cover;}

Css Media Queries:

@media screen and (max-width: 39.9375em) {
.slide-item{min-height: 280px;background-position: center;    background-size: cover;} }
@media screen and (min-width: 40em) {
.slide-item{ height: 360px; min-height: 360px;} }
@media screen and (min-width: 64em) {
.slide-item{ height: 600px; min-height: 600px;}}

JS:

$('.owl-carousel').owlCarousel(
{
    lazyLoad:true,
    items:1,
    autoplay: true,
    smartSpeed: 1500,
    nav:true,
    dots: true,
    loop : true,
  }
);
like image 33
Amazing Sey Avatar answered Sep 28 '22 10:09

Amazing Sey