Reputation: 6246
To vertically center <a>
tag i found this solution in this answer
you may use a pseudo element displayed as an inline-box using full height of li and vertical-aligned to midlle. DEMO
body, html {
height:100%;/ needed for demo */
}
nav {
height: 50%;/* increased for demo */
width: 100%;
}
nav ul {
height: 100%;
margin: 0px;
}
nav ul li {
height: 33%;
box-shadow:inset 0 0 0 1px;/* show me li , for demo */
}
nav ul li:before {
content:'';
height:100%;
display:inline-block;
vertical-align: middle;
}
My question why we have to use a pseudo element ?
Why it's not working when I delete the pseudo element and I put just :
a {
height:100%;
display:inline-block;
vertical-align: middle;
}
Is the vertical-align
have to apply to a first element (:before
) and the other (<a>
) will follow the vertical alignment ?
Upvotes: 1
Views: 816
Reputation: 85575
With the before and after pseudo-elements, we can insert virtual elements before or after an element's content. They both work the same way, except that one inserts the content before the element and the other inserts the content after.
Pseudo elements forces some contents to be there in the html page and in the css stylesheet you apply a empty content with the height of 100% ie. with your tag height and now the content is occupying the space before or after (as you use pseudo) and to that align vertically with options top, middle, or bottom:
try this fiddle : just set height: 100px;
and then increase manually like 200px, 300px then you will understand the exact reason
Without vertical alignment it's going to bottom as it is 100% heighty and if you use vertical-align:middle
then you'll notice how the pseudo is working.
You may understand by seeing this picture:
Upvotes: 1
Reputation: 10265
UPDATE:
using pseudo
element you are getting vertically center the text because of known height as you used height:100%;
on pseudo element.
As soon you will removed the height the layout will be broken.
As a tag is inline element
so you made it block level
element. but vertical-align: middle;
only work with display:table-cell
. but wait you have to use display:table
in li
element also.
Check the DEMO. so this piece of code will work..
a{
height:100%;
display: table-cell; /*replaced with display:inline-block*/
vertical-align: middle;
}
nav ul li {
height: 33%;
box-shadow:inset 0 0 0 1px;
display:table; /*add this line*/
width:100%; /*add width as well*/
}
Upvotes: 0