text-align:center doesn't work vertically in CSS, how can I get around this?

前端 未结 3 1366
情深已故
情深已故 2021-01-27 05:59

I\'m working with a div that\'s only holding text. It\'s using absolute positioning to center itself on top of an image div that is using relative positioning . I can center the

相关标签:
3条回答
  • 2021-01-27 06:38

    Try this...

    div {  position:absolute; top:50%; }
    

    and go through

    http://phrogz.net/CSS/vertical-align/index.html

    0 讨论(0)
  • 2021-01-27 06:47

    Try this one. Make the code as

    div { text-align:center; line-height:100%; } 
    
    0 讨论(0)
  • 2021-01-27 06:59

    As you guessed, you are right, text-align: center; is used to align the text/element horizontally only and not vertically... so if you are talking about aligning the single line text vertically than you need to use line-height, which will be equal to the container height

    Demo

    div {
        height: 100px;
        width: 100px;
        border: 1px solid #f00;
        line-height: 100px;
        text-align: center; /* Forgot this in the demo */
    }
    

    Where as if you are looking to vertical align entire element, than you can use either position: absolute; which I won't suggest you, instead use display: table-cell; nested inside display: table; parent

    Demo 2

    div {
        height: 100px;
        width: 100px;
        border: 1px solid #f00;
        display: table;
    }
    
    span {
        display: table-cell;
        vertical-align: middle;
        text-align: center;
    }
    
    0 讨论(0)
提交回复
热议问题