剪辑或蒙面Div上的CSS阴影

时间:2018-01-24 15:15:55

标签: html css css3

当鼠标悬停时,我有一个完整大小的div,但当鼠标消失时,所有边缘都会被剪裁。当div完全可见时,它会显示一个阴影,如下所示:

enter image description here

而不是上述内容,我想要反向阴影行为:当div被剪裁时显示阴影 并在div完全可见时隐藏阴影

也许剪裁不是正确的机制,我需要一个面具或另一个可以投射阴影的div?

body {
  margin: 30px;
}
.card {
  width: 300px;
  height: 100px;
  background: mediumslateblue;
  
  -webkit-clip-path: inset(20px 20px 20px 20px);
  clip-path: inset(20px 20px 20px 20px);
}

.card:hover {
  -webkit-clip-path: none;
  clip-path: none;
  
  -webkit-box-shadow: 2px 2px 5px 2px rgba(0, 0, 0, 0.3);
  -moz-box-shadow: 2px 2px 5px 2px rgba(0, 0, 0, 0.3);
  box-shadow: 2px 2px 5px 2px rgba(0, 0, 0, 0.3);
}
  <div class="card">
  </div>

2 个答案:

答案 0 :(得分:1)

我能想到的唯一解决方案是在将Sign-up or sign-in policy包装在容器中时使用filter: drop-shadow();

&#13;
&#13;
.card
&#13;
body {
  margin: 40px;
}
.card--wrapper {
  width: 400px;
  pointer-events: none;
}

.card--wrapper:not(:hover) {
  /* We want shadow on clipped box instead, now whole box */
  filter: drop-shadow(2px 2px 5px rgba(0, 0, 0, 0.3));
}

.card {
  width: inherit;
  height: 200px;
  background: mediumslateblue;
  pointer-events: auto;
  
  /* Clip div when not hovered */
  -webkit-clip-path: inset(20px 20px 20px 20px);
  clip-path: inset(20px 20px 20px 20px);
}

.card:hover {
  /* Show full div on hover */
  -webkit-clip-path: none;
  clip-path: none;
}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

不是剪切,而是将div放在具有以下属性的容器中:

.container {
  width: 360px;                      /* width when clipped */
  height: 160px;                     /* height when clipped */
  overflow: hidden;                  /* don't grow to match contents */
  transform: translate(20px, 20px);  /* maintain centering */
  box-shadow: 2px 2px 5px 2px rgba(0, 0, 0, 0.9);
}

将div设置为其全宽和高度,但将其转换为模拟剪裁:

.card {
  width: 400px;
  height: 200px;
  transform: translate(-20px, -20px);
}

将鼠标及其容器悬停时,请删除其翻译:

.container:hover, .card:hover {
  transform: none;
}

悬停容器时,将其宽度设置为div的宽度,将高度设置为auto,并删除box-shadow:

.container:hover {
  width: 400px;
  height: auto;
  box-shadow: none;
}

<强>段:

&#13;
&#13;
body {
  margin: 40px;
}

.card {
  background: yellow;
  width: 400px;
  height: 200px;
  transform: translate(-20px, -20px);
  font: 20px arial;
}

.container {
  width: 360px;
  height: 160px;
  overflow: hidden;
  transform: translate(20px, 20px);
  box-shadow: 2px 2px 5px 2px rgba(0, 0, 0, 0.9);
}

.container:hover, .card:hover {
  transform: none;
}

.container:hover {
  width: 400px;
  height: auto;
  box-shadow: none;
}
&#13;
<div class="container">
  <div class="card">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
  </div>
</div>
&#13;
&#13;
&#13;