0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

端点が接続した破線をCSSで描く方法

Posted at

イラレの破線みたいに端点が接続した破線をCSSで描く方法です。
dashed-lines1_w500.png

borderは使わずにlinear-gradient()で描いた1つのパターンをボックスの背景画像として上下左右のふちに繰り返し配置します。配置するパターンは下図のAで示した部分になります。
parts@2x-8.png
ポイントは、background-repeat: roundで画像Aを繰り返し配置すること。これにより、画像Aが互いに「隙間なく・切り取られることもなく」領域を埋めます。ただし、空間の大きさに帳尻を合わせるために画像は伸縮するので、表示された破線の線分の長さはCSSに指定したpx値から若干変動します。指定するpx値をうまく調整すれば目立ちません。

html
<div class="box dashed">
  <div class="inner"></div>
</div>

このサンプルでは、boxの内側を背景色lightcyanで塗りつぶしています。破線の隙間は透明にしたかったので、この背景色がboxのふちに染み出さないようにするためdiv.innerを設置しました。

css
.box {
  box-sizing: border-box;
  width: 80%; /* 適当に */
  padding: 4px; /* innerを設置する場合、線の太さ分あける */
  position: relative;
}

擬似要素でboxのoverlayを作り、上下左右のふちに相当する背景画像を一括で描きます。破線の線分の長さ20px, 太さ4px, 隙間10pxです。画像Aに相当する部分の幅は30pxになります。つまり、「塗り10px, 透明10px, 塗り10px」が1セットです。

css
.dashed::before {
  display: block;
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  pointer-events: none; /* box内にリンクがある場合、クリック可能にする */
  width: 100%;
  height: 100%;
  background-size: 30px 4px, 30px 4px, /* 上下 */
    4px 30px, 4px 30px; /* 左右 */
  background-position: top left, bottom left,
    top left, top right;
  background-repeat: round no-repeat, round no-repeat,
    no-repeat round, no-repeat round;
  background-image: linear-gradient(to right, blue, blue 10px,
    transparent 10px, transparent 20px, blue 20px),
    linear-gradient(to right, blue, blue 10px,
    transparent 10px, transparent 20px, blue 20px),
    linear-gradient(to bottom, blue, blue 10px,
    transparent 10px, transparent 20px, blue 20px),
    linear-gradient(to bottom, blue, blue 10px,
    transparent 10px, transparent 20px, blue 20px);
}

See the Pen [CSS] corner-aligned dashed lines by Kazuhiro Hashimoto (@kaz_hashimoto) on CodePen.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?