javascripthtmlcss

Force div to have an even width and height?


I have blurry text when using transform: translate(-50%,-50%); to center an absolutely positioned div on my screen.

I have tried tons of different solutions (mostly from here and here) and nothing works except making the width and height of the div an even number.

That is, if the height is 77px instead of 76px then the inner text is blurry. Likewise if the div width is 163 px instead of 162 px then it's blurry.

Is there a way to ensure the width and height of a dynamic div is an even number?

Using JavaScript seems like a no-go because not only is it complex but it would cause the element to flash to a different width immediately after being rendered (need to render it to first find out the width) which is unpleasant for the user to see.

Also, I can't just hardcode the width and height because the contents are dynamic. Also, if I could hardcode the width to, say, 100px, then I wouldn't even need this issue, because I could just do something like transform: translate(calc(-50% - 50px),-50%); to sidestep the issue.

Here's a code example:

.outer {
  margin: 0 auto;
  width: 500px;
  border: 1px solid #ddd;
  height: 50px;
  position: relative;
}

.inner {
  position: absolute;
  left: 50%;
  top: 25px;
  transform: translate(-50%, -50%);
  background-color: #dfdfdf;
  padding: 5px;
  font-family: Inter;
}
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">

<div class="outer">
  <div class="inner">
    <b> asdf </b> blurrya
  </div>
</div>


Solution

  • If you're willing to add one more element you can use flex within the absolutely positioned element to center the inner most element while maintaining its exclusion from the document flow.

    .outer {
      margin: 0 auto;
      width: 500px;
      border: 1px solid #ddd;
      height: 50px;
      position: relative;
    }
    
    .inner {
      position: absolute;  
      
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .center {
        top: 25px;
        background-color: #dfdfdf;
        padding: 5px;
        font-family: Inter;
    }
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
    
    <div class="outer">
      <div class="inner">
        <p class="center">
          <b>asdf </b> blurrya
        </p>
      </div>
    </div>