htmlcsscenteringborder-box

Perfectly center content of element with border and box-sizing


I set up a circular div with a circle inside using a html entity ⬤, the div is 20px wide and high and has a 2px border and box-sizing: border-box to stop the size fron increasing.

Typically to fill the whole div with the circle I'd also set the circle's font-size and line-height to 20px, but since 4px of the div is now taken up with border I set the line-height to 16px. This accounted for the vertical centering but the horizontal centering is still off.

How can I center it perfectly?

https://jsfiddle.net/3drve2xn/

 div{
   border: 2px solid #C15649;
   line-height:16px;
   font-size:20px;
   width:20px;
   height:20px;
   position: absolute;
   top:0;
   margin:0;
   padding:0;
   left:0;
   z-index: 1;
   text-align: center;
   color:black;
   border-radius: 50%;
   content:"\002B24";
   cursor: pointer;
   box-sizing: border-box;
}

enter image description here


Solution

  • does the output you look for look like this try to check it this fiddle and let me know if you still need more changes.

     div {
       border: 2px solid #C15649;
       width:20px;
       height:20px;
       position: relative;
       top:0;
       margin:0;
       padding:0;
       left:0;
       z-index: 1;
       text-align: center;
       color:black;
       border-radius: 50%;
       cursor: pointer;
       box-sizing: border-box;
    }
    div:before{
     position: absolute;
     content:"";
     top:0;
     bottom:0;
     background:black;
     border-radius:50%;
     left:0;
     right:0;
     margin:auto;
     width:100%;
     height:100%;
    }
    <div>
    </div>