如何仅在左侧和右侧设置框阴影

CSS 解决方案

如果我们只想在元素的左侧和右侧添加 box-shadow,我们建议我们考虑我们的代码片段中提供的一些方法。

或者许,最好的方法是使用带有“inset”值的 CSS box-shadow 属性。

另外,使用 :before 和 :after 伪元素,它们绝对位于元素的左右两侧。

使用 :before 和 :after 伪元素在左侧和右侧添加框阴影的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      div:before {
        box-shadow: -20px 0 20px -20px #001f9c inset;
        content: " ";
        height: 100%;
        left: -20px;
        position: absolute;
        top: 0;
        width: 20px;
      }
      div:after {
        box-shadow: 20px 0 20px -20px #001f9c inset;
        content: " ";
        height: 100%;
        position: absolute;
        top: 0;
        right: -20px;
        width: 20px;
      }
      div {
        background: none repeat scroll 0 0 #f0f1f5;
        height: 120px;
        margin: 30px;
        position: relative;
        width: 120px;
      }
    </style>
  </head>
  <body>
    <div></div>
  </body>
</html>

让我们看另一个没有 :before 和 :after 伪元素的例子。

在左侧和右侧添加框阴影的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      div {
        box-shadow: 12px 0 15px -4px rgba(0, 55, 162, 0.97), -12px 0 8px -4px rgba(0, 55, 162, 0.97);
        width: 120px;
        height: 120px;
        margin: 30px;
        background: #f0f1f5;
      }
    </style>
  </head>
  <body>
    <div></div>
  </body>
</html>

请注意,在上面的示例中,我们在元素的顶部和底部也有一点阴影。
但是我们可以在顶部和底部添加另外两个框阴影以掩盖可见的顶部和底部阴影。

在左右两侧设置 box-shadow 顶部和底部没有任何阴影的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      div {
        box-shadow: 0 9px 0px 0px #f0f1f5, 0 -9px 0px 0px #f0f1f5, 12px 0 15px -4px rgba(0, 55, 162, 0.97), -12px 0 15px -4px rgba(0, 55, 162, 0.97);
        width: 120px;
        height: 120px;
        margin: 30px;
        background: #f0f1f5;
      }
    </style>
  </head>
  <body>
    <div></div>
  </body>
</html>
日期:2020-06-02 22:14:54 来源:oir作者:oir