Friday, 6 January 2017

html - How do I vertically center text?




I've been working on getting the text in my content div centered vertically and I'm stumped. The container includes 1 div with a title and 1 div with content.



I've tried elements such as:



vertical-align: middle;


and also playing with the displays/positioning, but I'm not having any luck.



The current CSS is the following:



.content-wrapper {
height: 100vh;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: left;
text-align: left;
-ms-flex-flow: column nowrap;
flex-flow: column nowrap;
color: #000;
font-family: Montserrat;
text-transform: none;
-webkit-transform: translateY(40vh);
transform: translateY(40vh);
will-change: transform;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
-webkit-transition: all 1.7s cubic-bezier(0.22, 0.44, 0, 1);
transition: all 1.7s cubic-bezier(0.22, 0.44, 0, 1);
padding-top: 10%;
padding-right: 25px;
padding-left: 30px;
float: right;
width: 35%;
background-color: #f0f7fc;
}

Answer





Flexbox allows you to vertically align the text without having a div with a fixed height. It is now supported by all the modern browsers.



Check my other answer to see all the problems and workarounds for Flexbox. The majority are for Internet Explorer.



display: flex;
align-items: center;




div {
width: 50px;
height: 100px;
display: flex;
align-items: center;
border: 1px solid black;
}


Test







If you know the height of the external div, you can use line-height.



height: 100px;
line-height: 100px; /* same value as height */




div {
width: 50px;
height: 100px;
line-height: 100px;
border: 1px solid black;
}


Test







display: table-cell is another good alternative which allows you to vertically align without knowing the height of the div. It works in older browsers too (except Internet Explorer 7).



display: table-cell;
vertical-align: middle;




div {
width: 50px;
height: 100px;
display: table-cell;
vertical-align: middle;
border: 1px solid black;
}


Test




No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...