Vertically and horizontally centering text in circle in CSS (like iphone notification badge)

后端 未结 5 629
伪装坚强ぢ
伪装坚强ぢ 2020-12-04 06:50

I\'m looking for a way of to do a cross-browser iphone-like badge in CSS3. I\'d obviously like to use one div for this, but alternative solutions would be fine. The importan

5条回答
  •  有刺的猬
    2020-12-04 07:05

    Horizontal centering is easy: text-align: center;. Vertical centering of text inside an element can be done by setting line-height equal to the container height, but this has subtle differences between browsers. On small elements, like a notification badge, these are more pronounced.

    Better is to set line-height equal to font-size (or slightly smaller) and use padding. You'll have to adjust your height to accomodate.

    Here's a CSS-only, single

    solution that looks pretty iPhone-like. They expand with content.

    Demo: http://jsfiddle.net/ThinkingStiff/mLW47/

    Output:

    enter image description here

    CSS:

    .badge {
        background: radial-gradient( 5px -9px, circle, white 8%, red 26px );
        background-color: red;
        border: 2px solid white;
        border-radius: 12px; /* one half of ( (border * 2) + height + padding ) */
        box-shadow: 1px 1px 1px black;
        color: white;
        font: bold 15px/13px Helvetica, Verdana, Tahoma;
        height: 16px; 
        min-width: 14px;
        padding: 4px 3px 0 3px;
        text-align: center;
    }
    

    HTML:

    1
    2
    3
    44
    55
    666
    777
    8888
    9999

提交回复
热议问题