Center vertically a unknown height text in a unknown height div

后端 未结 3 2618
轮回少年
轮回少年 2021-02-20 15:00

I know this is a common issue, and I\'ve already asked a similar one. But I could not find the solution this time. I am trying to vertically center a text which can have differe

相关标签:
3条回答
  • 2021-02-20 15:23

    CSS with display solution:

    #test {
      display:table; 
    }
    
    #sumup {
      display:table-cell; 
    }
    

    The Demo http://jsfiddle.net/F8TtE/7/

    0 讨论(0)
  • 2021-02-20 15:24

    Here it is :

    #test {
        text-align:center;
    }
    #test::before {
        content: '';
        display: inline-block;
        height: 100%;
        vertical-align: middle;
    }
    #sumup {
        display: inline-block;
        vertical-align: middle;
    }
    

    #test {
        height : 180px;
        text-align:center;
        background: yellow;
    }
    
    #sumup {
       	background-color: #123456;
    }
    
    #test:before {
        content: '';
        display: inline-block;
        height: 100%;
        vertical-align: middle;
      }
      #sumup {
        display: inline-block;
        vertical-align: middle;
      }
    <div id="test">
    		<div id="sumup">
    			
    			<h1 class="titre">Title</h1>
    			<div id="date">hello guys</div>
    		</div>
    </div>


    EDIT: It's now 2015 and thankfully the web changes. Assuming you don't support obsolete browsers, it's usually simpler and cleaner to vertically center elements with the Flex model.

    #test {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }
    

    #test {
        height : 180px;
        background: yellow;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }
    
    #sumup {
       	background-color: #123456;
    }
    <div id="test">
    		<div id="sumup">
    			<h1 class="titre">Title</h1>
    			<div id="date">hello guys</div>
    		</div>
    </div>

    0 讨论(0)
  • 2021-02-20 15:35

    Here's another way using display:table-cell since I don't quite understand how dystroy's answer works.

    #test {
        width:100%;
        height : 400px;
        display:table;
    }
    
    #sumup {
        width : 100%;
    
        height : 100%;
        background-color: #123456;
        display:table-cell;
        vertical-align:middle;
    }
    

    http://jsfiddle.net/F8TtE/3/

    0 讨论(0)
提交回复
热议问题