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

▼魔方 西西 提交于 2019-12-06 08:45:53

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

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%) 
}

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;
}
Lorenz Merdian

As a further alternative, you might use flexbox

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

(stolen from this stackoverflow question)

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