Home > Software design >  How to vertically center text when using the :before modifier in CSS?
How to vertically center text when using the :before modifier in CSS?

Time:12-28

This is another "how do I vertically center" question in HTML. This one is when using the :before modifier.

HTML

<div style="border: 1px solid blue">
  <div >vertically center me</div>
</div>

CSS

.status-yellow {
    display: inline-block;
    padding: .35em .65em;
    font-size: .75em;
    font-weight: 400;
    line-height: 1;
    color: #000;
    text-align: center;
    white-space: nowrap;
    vertical-align: baseline;
    text-transform: uppercase;
    background-color: #fff;
}

.status-yellow:before {
    display: inline-block;
    content:"\2022";
    margin-right: 0.5rem;
    color: yellow;
    font-size: 48px;
}

Here's a CodePen showing the issue

I have a div tag and I'm using the :before modifier to inject a bullet before the text. When the bullet increases in size, the vertical centering doesn't work. When the bullet is tiny (too tiny) it's all centered. I'm missing something. What am I missing?

CodePudding user response:

You can use flexbox.

.status-yellow {
    display: inline-block;
    padding: .35em .65em;
    font-size: .75em;
    font-weight: 400;
    line-height: 1;
    color: #000;
    text-align: center;
    white-space: nowrap;
    vertical-align: baseline;
    text-transform: uppercase;
    background-color: #fff;
    display:flex;
    align-items:center;/*for vertical align*/
    justify-content:center;/*for horizontal align*/
}

.status-yellow:before {
        display: inline-block;
        content:"\2022";
        margin-right: 0.5rem;
        color: yellow;
        font-size: 48px;
    }
  • Related