Search code examples
htmlcssbackground-color

Explanation of a html and css trick for label background color


How can I make a performance like following image using HTML and CSS?

I mean, how the outlined label can disappear the border partially? Background color of the label supposedly is transparent!


Solution

  • You can use mix-blend-mode and isolation: isolate for masking parts of the border:

    /*Blacks will persist, whites will be transparent*/
    .border-label {
      mix-blend-mode: multiply;
      
      position: absolute;
      border: 2px solid black;
      background-color: white;
    }
    .border-label>label {
      /*Position centered on top border*/
      position: absolute;
      top: 0;
      transform: translateY(-50%);
      
      color: black;
      background-color: white;
    }
    
    /*Ignore, presentational; remaining styles and focus behaviour*/
    body {background-color: red}
    
    .input-wrapper {
      position: relative;
      background-color: yellow;
    }
    .input-wrapper>input {
      margin: 0;
      border: 0 none;
      padding: .6rem .8rem;
      width: 100%;
      height: 100%;
      display: block;
      font-size: inherit;
      background-color: transparent;
      outline: none;
    }
    
    .border-label {
      top: -2px;
      left: -2px;
      border-radius: 4px;
      width: 100%;
      height: 100%;
      transition: border-color .05s;
      pointer-events: none;
    }
    input:not(:focus)+.border-label {
      border-color: transparent;
    }
    
    .border-label>label {
      left: 0;
      margin-left: .2rem;
      padding: .2rem .4rem;
      display: inline-block;
      transition: top .05s;
    }
    
    input:not(:focus, :valid)+.border-label>label {
      top: 50%;
    }
    <div class="input-wrapper">
      <input required>
      <div class="border-label">
        <label>Placeholder label</label>
      </div>
    </div>

    Unfortunately I'm not experienced enough with blend-modes and masking, so someone else may surely be able to improve my answer.