Home > Back-end >  hr vertical centered in a div
hr vertical centered in a div

Time:11-05

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 >
  <hr>
</div>

CodePudding user response:

The bigger problem is that you need to remove any margin from the hr by adding a margin:0

Additionally you can get a more concise and understandable code by changing the transform:translateY() to a top:calc() and removing bottom:

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

hr {
    height: 4px; 
    margin:0;
    background-color: cadetblue;
    position: absolute;
    right: 0;
    top: calc(50% - 2px);
    left: 0;
}
<div >
  <hr>
</div>

CodePudding user response:

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 >
  <hr>
</div>

CodePudding user response:

No need to use transform in css.

.container {
    position: relative;
    width: 99%;
    height: 50vh;
    border: solid 4px #333;
}

hr {
    height: 5px;
    background-color: blue;
    position: absolute;
    right: 0;
    left: 0;
    top: calc(50% - 5px);
    margin: 0;
}
<div >
  <hr>
</div>

In the top class define your hr height

  • Related