【CSS】inputを装飾する方法

updated 2021-7-30

type="text"

シンプル

HTML

<input type="text" name="any" autocomplete />

CSS

input[type=text] {
  padding: .5rem;
  border: 1px solid #ddd;
}
input[type=text]:focus-visible {
  outline: violet auto 1px;
}

type="checkbox"

シンプル

HTML

<input type="checkbox" name="consent" id="consent" />
<label for="consent" class="consent">同意しますか?</label>

CSS

input[type=checkbox] {
  opacity: 0;
}
label.consent {
  position: relative;
}
label.consent::before {
  content: "";
  display: inline-block;
  width: 1rem;
  height: 1rem;
  border: 1px solid #ddd;
  border-radius: 3px;
  position: relative;
  margin-right: .5rem;
  transform: translateY(.2rem);
}
label.consent::after {
  content: "";
  display: block;
  height: 1rem;
  width: .6rem;
  border-right: 3px solid #354962;
  border-bottom: 3px solid #354962;
  opacity: 0;
  transform: rotate(40deg);
  position: absolute;
  top: -.1rem;
  left: .2rem;
}
/* animation */
input[type=checkbox]:checked + label.consent::after {
  opacity: 1;
}

SVG+シンプル

HTML

<input type="checkbox" name="item" id="check-item" />
<label for="check-item" class="check-item">
  <svg viewBox="0 0 64 64" width="1rem" height="1rem">
    <use xlink:href="assets/simple-checkbox.svg#check"></use>
  </svg>
  チェックリスト1
</label>

CSS

input[type=checkbox] {
  opacity: 0;
}
label.check-item {
  position: relative;
}
label.check-item::before {
  content: "";
  display: inline-block;
  width: 1rem;
  height: 1rem;
  border: 1px solid #ddd;
  border-radius: 3px;
  position: relative;
  margin-right: .5rem;
  transform: translateY(.2rem);
}
label.check-item > svg {
  position: absolute;
  left: .05rem;
  top: .3rem;
  opacity: 0;
}
/* animation */
 input[type=checkbox]:checked + label.check-item > svg {
  opacity: 1;
}

SVG+アニメーション

HTML

<input type="checkbox" name="item" id="anim-item" />
<label for="anim-item" class="check-item">
  <svg width="16" height="16" id="checkbox" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path id="check" d="M8.49995 37.0805L21.9471 47.7579C23.9627 49.3584 26.864 49.1673 28.6522 47.3163L53.9998 21.0796" stroke="black" stroke-width="5" stroke-linecap="round"/>
  </svg>
  アニメーション
</label>

CSS

input[type=checkbox] {
  opacity: 0;
}
label.check-item {
  position: relative;
}
label.check-item::before {
  content: "";
  display: inline-block;
  width: 1rem;
  height: 1rem;
  border: 1px solid #ddd;
  border-radius: 3px;
  position: relative;
  margin-right: .5rem;
  transform: translateY(.2rem);
}
svg#checkbox {
  position: absolute;
  left: .05rem;
  top: .3rem;
}
svg#checkbox > path {
  stroke-dasharray: 4000;
  stroke-width: 4;
  stroke: black;
}
/* animation */
input[type=checkbox] + .check-item svg#checkbox > path {
  stroke-dashoffset: 4000;
  transition: none;
}
input[type=checkbox]:checked + .check-item svg#checkbox > path {
  stroke-dashoffset: 0;
  transition: stroke-dashoffset 4s linear;
}

参考

whatwg input