Monday 25 November 2019

html - How do I vertically center text with CSS?

Another way (not mentioned here yet) is with Flexbox.



Just add the following code to the container element:



display: flex;
justify-content: center; /* align horizontal */
align-items: center; /* align vertical */







.box {
height: 150px;
width: 400px;
background: #000;
font-size: 24px;

font-style: oblique;
color: #FFF;
text-align: center;
padding: 0 20px;
margin: 20px;
display: flex;
justify-content: center;
/* align horizontal */
align-items: center;
/* align vertical */

}


Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh





Alternatively, instead of aligning the content via the container, flexbox can also center the a flex item with an auto margin when there is only one flex-item in the flex container (like the example given in the question above).




So to center the flex item both horizontally and vertically just set it with margin:auto







.box {
height: 150px;
width: 400px;
background: #000;

font-size: 24px;
font-style: oblique;
color: #FFF;
text-align: center;
padding: 0 20px;
margin: 20px;
display: flex;
}
.box span {
margin: auto;

}


margin:auto on a flex item centers it both horizontally and vertically





NB: All the above applies to centering items while laying them out in horizontal rows. This is also the default behavior, because by default the value for flex-direction is row. If, however flex-items need to be laid out in vertical columns, then flex-direction: column should be set on the container to set the main-axis as column and additionally the justify-content and align-items properties now work the other way around with justify-content: center centering vertically and align-items: center centering horizontally)








.box {
height: 150px;
width: 400px;
background: #000;
font-size: 18px;
font-style: oblique;

color: #FFF;
display: flex;
flex-direction: column;
justify-content: center;
/* vertically aligns items */
align-items: center;
/* horizontally aligns items */
}
p {
margin: 5px;

}



When flex-direction is column...



"justify-content: center" - vertically aligns



"align-items: center" - horizontally aligns







A good place to start with Flexbox to see some of its features and get syntax for maximum browser support is flexyboxes



Also, browser support nowadays is very good: caniuse




For cross-browser compatibility for display: flex and align-items, you can use the following:



display: -webkit-box;
display: -webkit-flex;
display: -moz-box;
display: -ms-flexbox;
display: flex;
-webkit-flex-align: center;
-ms-flex-align: center;
-webkit-align-items: center;

align-items: center;

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...