四个角的故事(CSS边框四个角自定义样式)

8,129 阅读1分钟


直奔主题,我们要形成上图的四个角高亮(不同色)。有两种方法如下:

方法一

利用after、before伪元素,覆盖元素本身的边框,保留四个角不覆盖。

  <div class="corner">四个角</div>
  <style>
      body{
          background: -webkit-linear-gradient(0deg, #0840C8, #06297D);
          height: 100vh;
      }
      div{
          width: 300px;
          height: 300px;
          color: white;
      }
      .corner{
          position: relative;
          border: 1px solid #81BCFF;
      }
      .corner:after{
          content: '';
          width: calc(100% - 24px);
          height: 100%;
          position: absolute;
          left: 12px;
          top: -1px;
          bottom: -1px;
          border-bottom: 1px solid rgba(31, 73, 138, 0.7);
          border-top: 1px solid rgba(31, 73, 138, 0.7);
      }
      .corner:before{
          content: '';
          width: 100%;
          height: calc(100% - 24px);
          position: absolute;
          left: -1px;
          right: -1px;
          top: 12px;
          border-left: 1px solid rgba(31, 73, 138, 0.7);
          border-right: 1px solid rgba(31, 73, 138, 0.7);
      }
  </style>

方法二

利用四个空标签,分别定义四个角的样式。这种方法相对灵活一些,四个角的样式可以各不相同。

  <div class="corner">四个角
      <span class="top-left"></span>
      <span class="top-right"></span>
      <span class="bottom-left"></span>
      <span class="bottom-right"></span>
  </div>
  <style>
      body{
          background: -webkit-linear-gradient(0deg, #0840C8, #06297D);
          height: 100vh;
      }
      div{
          width: 300px;
          height: 300px;
          color: white;
      }
      .corner{
          position: relative;
          border: 1px solid rgba(31, 73, 138, 0.7);

      }
      .top-left{
          position: absolute;
          left: -1px;
          top: -1px;
          padding: 10px;
          border-style: solid;
          border-color: red;
          border-width: 1px 0 0 1px;
      }
      .top-right{
          position: absolute;
          right: -1px;
          top: -1px;
          padding: 10px;
          border-style: solid;
          border-color: #81BCFF;
          border-width: 1px 1px 0 0;
      }
      .bottom-left{
          position: absolute;
          right: -1px;
          bottom: -1px;
          padding: 10px;
          border-style: solid;
          border-color: yellow;
          border-width: 0 1px 1px 0;
      }
      .bottom-right{
          position: absolute;
          left: -1px;
          bottom: -1px;
          padding: 10px;
          border-style: solid;
          border-color: #ccc;
          border-width: 0 0 1px 1px;
      }

  </style>