CSS how to vertically align text within a pseudo element

為{幸葍}努か 提交于 2020-02-22 06:11:29

问题


I have created a pseudo element to sit over an unordered list, the css is as follows:

.pricing-column.featured::after {
    content: "Most Popular";
    background: #52BDE6 none repeat scroll 0% 0%;
    color: #FFF;
    width: 80px;
    border-radius: 100%;
    position: absolute;
    top: -10px;
    left: -10px;
    z-index: 1000;
    text-transform: uppercase;
    font-weight: 700;
    font-size: 0.9em;
    line-height: 0.9em;
    padding: 10px;
    display: inline-block;
    height: 80px;
}

However, with this, the text inside the pseudo element sits at the top of my element - is there a way to center it vertically?

Here is a fiddle http://jsfiddle.net/6dqxt2r3/


回答1:


Easiest way? Add padding top. Little more difficult but better way, use flexbox.

These properties will do

display: -webkit-flex;
display: flex;
-webkit-flex-direction: column;
flex-direction: column;
-webkit-align-items: center;
align-items: center;
-webkit-justify-content: center;
justify-content: center;
text-align: center;

http://jsfiddle.net/6dqxt2r3/4/




回答2:


If you want to center it verticaly use top: calc(50% - 40px); 40px is half of the element

Updated fiddle

EDIT:

Sorry, update use display: inline-flex; and align-items: center;

Fiddle




回答3:


As long as you can change how you position the pseudo element then this will work.

Change position: absolute; to position: relative; and adjust the top and left values accordingly.

To center the text apply display: table-cell;, text-align: center; and vertical-align: middle.

.pricing-column.featured::after {
    content: "Most Popular";
    background: #52BDE6 none repeat scroll 0% 0%;
    color: #FFF;
    width: 80px;
    border-radius: 100%;
    position: relative;
    top: -35px;
    left: -90px;
    z-index: 1000;
    text-transform: uppercase;
    font-weight: 700;
    font-size: 0.9em;
    line-height: 0.9em;
    padding: 10px;
    display: table-cell;
    height: 80px;
    text-align: center;
    vertical-align: middle;
}

http://jsfiddle.net/hungerstar/6dqxt2r3/5/



来源:https://stackoverflow.com/questions/33154116/css-how-to-vertically-align-text-within-a-pseudo-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!