首页 > 解决方案 > How to add box-shadow to bootstrap carousel image?

问题描述

I want to have a inset box-shadow over my images in a bootstrap carousel but whatever I do it doesn't work. I want the shadow just around the borders of the image.

Here is my code:

.carousel-item {
    width: 100%;
}
.carousel-item>a>img {
    width: 400px;
    height: 600px;
}
.carousel-item>a>img::after {
    box-shadow: 0px 0px 60px 40px black inset;
    bottom: 0;
    content: "";
    display: block;
    left: 0;
    position: absolute;
    right: 0;
    top: 0;
}
    
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
    <div id="content"> 

<div id="demo" class="carousel slide" data-ride="carousel">
    <div class="carousel-inner">
        <div class="carousel-item">
            <a href="/2/">
                <img src="https://www.w3schools.com/bootstrap4/chicago.jpg">
            </a>
        </div>
        
        <div class="carousel-item">
            <a href="/4/">
                <img src="https://www.w3schools.com/bootstrap4/chicago.jpg">
            </a>
        </div>
        
        <div class="carousel-item">
            <a href="/3/">
                <img src="https://www.w3schools.com/bootstrap4/chicago.jpg">
            </a>
        </div>
    </div>
</div>

    </div>

标签: javascripthtmlcss

解决方案


From the CSS Spec:

The ':before' and ':after' pseudo-elements can be used to insert generated content before or after an element's content.

Since an img doesn't have actual content, it makes sense that ::before and ::after cannot be accessed here.

One thing you can do is add a wrapper around the img and proceed from there.

.img-container {
  display: inline-block;
  position: relative;
}

.img-container::after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  box-shadow: 0px 0px 60px 40px black inset;
}
<div class="img-container">
  <img src="http://placekitten.com/300/200" alt="">
</div>

jsFiddle


推荐阅读