Skip to content

Instantly share code, notes, and snippets.

@softiconic
Last active December 2, 2023 18:58
Show Gist options
  • Save softiconic/e8ea17311d6dc6966927687cc4f19272 to your computer and use it in GitHub Desktop.
Save softiconic/e8ea17311d6dc6966927687cc4f19272 to your computer and use it in GitHub Desktop.
Convert an image source (img src) into a background image using a combination of script and CSS.
//Replace carousel images into background images.
$('#carousel .item img').each(function() {
var imgSrc = $(this).attr('src');
$(this).parent().css({'background-image': 'url('+imgSrc+')'});
$(this).remove();
});
<div class="slider-block">
<div id="carousel" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner" role="listbox">
<div class="item active">
<img src="images/slider1.jpg" class="img-responsive" alt="">
</div>
<div class="item">
<img src="images/slider1.jpg" class="img-responsive" alt="">
</div>
<div class="item">
<img src="images/slider1.jpg" class="img-responsive" alt="">
</div>
</div>
<!-- Controls -->
<a class="left carousel-control" href="#carousel" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#carousel" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
.slider-block{
height:350px;
display:inline-block;
}
#carousel {
height:100%;
}
#carousel .carousel-inner{
height:100%;
}
#carousel .item{
background-repeat:no-repeat;
background-size:cover;
background-position:center center;
width:100%;
height:100%;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment