Home > Article > Web Front-end > Reasons why CSS vertical alignment doesn't work and how to solve it
verticla-align is used to adjust the vertical position of inline elements, but sometimes it doesn't work. This article will share with you the reasons and solutions for CSS vertical alignment not working.
Let’s first analyze the reasons that cause vertical alignment to be invalid
I think many people will encounter such a problem when using vertical-align as an attribute to align vertically Location, for some reason it doesn't work at all!
In fact, vertical-align can only be used for "inline elements" and "table cells".
How to use vertical-align
Describe where you want to align in an "inline element" or "table cell".
"Want to change the base line of text" if applied to inner elements. The base line of text is the default position.
This position can be raised or lowered.
Basically there are top, bottom, and middle, which can also be specified by numbers in pixels and %.
If applicable to table cells, it is "when aligned in the vertical direction".
Let’s look at a specific example:
For example, if you want to use vertical-align to achieve vertical centering, please see the following code.
We first prepare such a box
HTML
<div class ="box-wrap"> <div class ="box"> <p>文字内容</p> </div> </div>
CSS
.box{ background-color: #66b6d5; width: 300px; height: 200px; } p{ color: #fff; }
The effect is as follows:
Then add display: table - cell; and vertical - align: middle; to .box.
.box{ display: table-cell; vertical-align: middle; background-color: #66b6d5; width: 300px; height: 200px; } p{ color: #fff; }
The effect is as follows: vertical centering is achieved
It should be noted here that in order to achieve vertical position specification, a height is required table.
If you want the height to depend on the parent element, make sure you specify the parent element as display: table; and also hight.
The same goes for the difference between vertical and aligned, top and bottom.
The code is as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style type="text/css"> .box-wrapper{ display: table; height: 200px; } .box{ width: 300px; background-color: #66b6d5; display: table-cell; border: 1px #fff solid; } .box.middle{ vertical-align: middle; } .box.top{ vertical-align: top; } .box.bottom{ vertical-align: bottom; } p{ color: #fff; } </style> </head> <body> <div class="box-wrapper"> <div class="box middle"> <p>文字内容</p> </div> <div class="box top"> <p>文字内容</p> </div> <div class="box bottom"> <p>文字内容</p> </div> </div> </body> </html>
The effect is as follows:
The above is the detailed content of Reasons why CSS vertical alignment doesn't work and how to solve it. For more information, please follow other related articles on the PHP Chinese website!