Mathieu Marques Mathieu Marques - 2 months ago 6
CSS Question

How to center a character that is larger than its container

I have icons that I want centered both horizontally and vertically.

See codepen and snippet below:



div {
border: 1px solid black;
}
.icon-placeholder {
height: 34px;
overflow: hidden;
width: 34px;
}
.icon {
color: hotpink;
font-size: 400%;
}
.icon::before {
content: '+';
}

<div class="icon-placeholder">
<span class="icon"></span>
</div>





How can I do that regardless of
.icon
's font size.

I have tried
transform
,
position: absolute
,
display: table
with no luck. I can't use flex.

Answer

On thing to note though, a + isn't necessarily centered in the first place depending on the font.

div {
  border: 1px solid black;
}

.icon-placeholder {
  height: 34px;
  overflow: hidden;
  position: relative;
  width: 34px;
}

.icon {
  color: hotpink;
  font-size: 400%;
}

.icon::before {
  content: '0';
  display: inline-block;
  position: absolute;
  right: 50%;
  bottom: 50%;
  transform: translate(50%, 50%);
}
<div class="icon-placeholder">
  <span class="icon"></span>
</div>