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

后端 未结 5 651
伪装坚强ぢ
伪装坚强ぢ 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:16

    Interesting question! While there are plenty of guides on horizontally and vertically centering a div, an authoritative treatment of the subject where the centered div is of an unpredetermined width is conspicuously absent.

    Let's apply some basic constraints:

    • No Javascript
    • No mangling of the display property to table-cell, which is of questionable support status

    Given this, my entry into the fray is the use of the inline-block display property to horizontally center the span within an absolutely positioned div of predetermined height, vertically centered within the parent container in the traditional top: 50%; margin-top: -123px fashion.

    Markup: div > div > span

    CSS:

    body > div { position: relative; height: XYZ; width: XYZ; }
    div > div { 
      position: absolute;
      top: 50%;
      height: 30px;
      margin-top: -15px; 
      text-align: center;}
    div > span { display: inline-block; }
    

    Source: http://jsfiddle.net/38EFb/


    An alternate solution that doesn't require extraneous markups but that very likely produces more problems than it solves is to use the line-height property. Don't do this. But it is included here as an academic note: http://jsfiddle.net/gucwW/

提交回复
热议问题