V is for vertically centering text and icons
In the original screencast video for the vertical-align
property, we looked at a couple of methods for centering elements vertically. In this article we’ll outline three different methods for vertical centering - something that always used to be quite tricky but is now a breeze to accomplish.
Use line-height
for simple vertical centering
To vertically center a single line of text or an icon within its container, we can use the line-height
property. This property controls the height
of a line in a run of text and adds an equal amount of space above and below the line-box of inline elements. If the height
of the container is known, then setting a line-height
of the same value will vertically center the child elements.
[code language="css"]
.container {
width: 200px;
height: 200px;
line-height: 200px;
}
[/code]
Use position
and transform
for flexible vertical centering
The line-height
method above is quick and dirty but relies on fixed heights. I tend to avoid setting height
explicitly as it can often restrict the flow of content in a responsive project. This technique is not flexible enough if you’re working with elements of variable or fluid height
.
Instead, we can combine position
and translations to vertically center variable height
elements. For example, to vertically center an element within the whole height
of the viewport, we could use the following snippet:
[code language="css"]
.container {
position: relative;
min-height: 100vh;
}
.vertical-center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
[/code]
We first create a positioning context by setting position:relative
on a container element. This will then allow us to position the .vertical-center
element within its boundaries.
Continue reading %AtoZ CSS Quick Tip: How to Vertically Center Text and Icons%
by Guy Routledge via SitePoint
No comments:
Post a Comment