How to vertically align text in the middle of a div that has a percentage height? [duplicate]

拈花ヽ惹草 提交于 2019-12-10 10:38:54

问题


Here is what I have right now. In other divs using vertical-align:middleand setting the line-height to the same value as the height property it should work!The only thing is that in those divs I used pixel dimension and not percentages. Can anybody tell me why this wont work with percentages? also setting the text-sizeto 50% should also make text half the size of the div but it is really really small still? What is going on here?

#chooseStateAlabama {
    width: 20%;
    height: 25%;
    top: 0;
    left: 0;
    position: absolute;
    background: url(../_images/_unitedStates/_states/chooseStateAlabama.png);
    background-size: 100% 200%;
    float: left;
    color: #FFFFFF;
    font-family: Arial;
    font-style: normal;
    font-weight: bold;
    font-size: 50%;
    line-height: 25%;
    text-align: center;
    vertical-align: middle;
}

回答1:


You can use display:inline-block , height:100% and vertical-align:middle to a single element or pseudo element aside the text (before or after): DEMO

#chooseStateAlabama:before {/* this can be an extra tag within HTML structure if pseudo used for other purpose */
    content:'';
    display:inline-block;
    height:100%;
    vertical-align:middle;
}

If you happen to have more content or more than 1 line, then use an element to wrap it as well and apply to it display and vertical-align. DEMO2 to see behavior




回答2:


http://jsfiddle.net/L85h8vvj/7/

HTML

<body>
<div class='container4'>
    <div>Example :)</div>
</div>
</body>

CSS

body{
    margin:0px;
}
div.container4 {
height: 100%;
width:100%;
position: absolute;
}

div.container4 div {
margin: 0;
background: yellow;
position: absolute;
top: 50%;
left: 50%;
margin-right: 50-%;
transform: translate(-50%, -50%) 
}



回答3:


If you can alter the markup you can use quite a few ways to get the result you want.

http://jsfiddle.net/vvpn6cge/

Because you have text ( that could be one or many lines long I guess) then you could get the result using CSS table cells (see the fiddle).

.outer-container {
   display: table;
   width: 100%;
}
.txt-vertical-align {
   display: table-cell;
   text-align: center;
   vertical-align: middle;
}



回答4:


As a further alternative, you might use flexbox

display: flex;
justify-content:center;
align-content:center;
flex-direction:column;

(stolen from this stackoverflow question)



来源:https://stackoverflow.com/questions/25853679/how-to-vertically-align-text-in-the-middle-of-a-div-that-has-a-percentage-height

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