My goal is to center a single character, using CSS, in a span
that is smaller than the character itself.
The setup I have is:
<span id="A">X</span><span id="B">Y</span><span id="C">Z</span>
All three spans are styled with:
display: inline-block;
width: 32px;
height: 32px;
The Y character in the middle span is larger than the span itself. My aim is to have the character centered over the span, overlapping both X and Z.
When Y is smaller than the span, vertical alignment and text centering rules work:
vertical-align: middle;
text-align: center;
However, when Y is wider than the containing box, these rules no longer apply and the Y character shifts to the right. How can I horizontally center Y when it exceeds the width of the container?
(I attempted to use display: table-cell
, as suggested in other solutions, but this did not work because the width: 32px
was then disregarded.)
Here is my attempted solution: https://jsfiddle.net/seehuhn/hec3xucu/
span {
display: inline-block;
width: 32px;
height: 32px;
font: bold 32px/32px courier;
position: relative;
vertical-align: middle;
text-align: center;
}
#A {
background: red;
}
#B {
background: #8f8;
font-size: 92px;
color: #F99;
z-index: 1;
}
#C {
background: blue;
}
<p><span id="A">X</span><span id="B">Y</span><span id="C">Z</span>