如何使用线性渐变,无论容器尺寸如何,都要使纯css水平/垂直和特定厚度的角线始终居中

时间:2017-03-14 19:27:55

标签: css background linear-gradients

我正在尝试制作三种类型的矩形瓷砖,无论它们的尺寸如何都应该

  1. 一个20像素宽的垂直居中的水平线
    1. 一条20像素宽的水平居中垂直线
      1. 一条“角”线,两条边穿过瓷砖的edfes中心,宽度为20像素
      2. 我尝试使用线性渐变来完成这项工作,但我设法用百分比来制作一些接近(但不完全)的东西..

        <div class="small corner-bg"></div>
        <div class="small vertical-bg"></div>
        <div class="small horizontal-bg"></div>
        <div class="big corner-bg"></div>
        <div class="big vertical-bg"></div>
        <div class="big horizontal-bg"></div>
        
        .small {
          width: 100px;
          height: 30px;
          border: 1px solid red;
        }
        
        .big {
          width: 400px;
          height: 50px;
          border: 1px solid red;
        }
        
        .vertical-bg {
            background-image: linear-gradient(90deg, transparent 33%, #0033a0 33%, #0033a0 66%, transparent 66%);
        }
        
        .horizontal-bg {
            background-image: linear-gradient(transparent 33%, #0033a0 33%, #0033a0 66%, transparent 66%);
        }
        
        .corner-bg {
            background-image: linear-gradient(transparent 66%, #003580 33%), linear-gradient(90deg, transparent 66%, #003580 33%);
            background-repeat: no-repeat;
            background-position: -18px -12px;
        }
        

        https://jsfiddle.net/tq7aqs78/

        以下是我所取得的成就和我所需要的:enter image description here

1 个答案:

答案 0 :(得分:0)

我让它的工作方式如下所示:

.small {
  width: 100px;
  height: 30px;
  border: 1px solid red;
}

.big {
  width: 400px;
  height: 50px;
  border: 1px solid red;
}

.horizontal-bg {
    background-image: linear-gradient(transparent calc(50% - 5px), #000 calc(50% - 5px), #000 calc(50% + 5px), transparent calc(50% + 5px));
}

.vertical-bg {
    background-image:  linear-gradient(90deg,transparent calc(50% - 5px), #000 calc(50% - 5px), #000 calc(50% + 5px), transparent calc(50% + 5px));
}

.corner-bg {
    background-image: 
    linear-gradient(90deg,transparent calc(50% + 5px), white calc(50% + 5px), white calc(60% + 5px)),
    linear-gradient(transparent calc(50% + 5px), white calc(50% + 5px), white calc(60% + 5px)),
    linear-gradient(transparent calc(50% - 5px), #000 calc(50% - 5px), #000 calc(50% + 5px), transparent calc(50% + 5px)), 
    linear-gradient(90deg,transparent calc(50% - 5px), #000 calc(50% - 5px), #000 calc(50% + 5px), transparent calc(50% + 5px));

    background-repeat: no-repeat;
}

https://jsfiddle.net/tq7aqs78/3/