Search code examples
htmlcsscss-position

hr vertical centered in a div


How to center a HR tag vertically in a div, i tried this but its not centered perfectly

.container {
    position: relative;
    width: 80vw;
    height: 40vh;
    border: solid 4px #333;
}

hr {
    height: 5px;
    background-color: cadetblue;
    position: absolute;
    right: 0;
    top: 50%;
    left: 0;
    transform: translateY(-100%);
}
<div class="container">
  <hr>
</div>


Solution

  • Change transform to translateY(-50%); and add margin: 0; to the hr:

    (BTW: No need for top and bottom settings if you have a defined height, having one of those is sufficient)

    .container {
        position: relative;
        width: 80vw;
        height: 40vh;
        border: solid 4px #333;
    }
    
    hr {
        height: 5px;
        background-color: cadetblue;
        position: absolute;
        right: 0;
        top: 50%;
        left: 0;
        transform: translateY(-50%);
        margin: 0;
    }
    <div class="container">
      <hr>
    </div>