Q is for Questions about CSS
There is literally nothing else to say on the topic of CSS quotes, nor is there any other selector, property or value that starts with Q. So, in this week’s tips, I answer some common questions I get from my students, AtoZ supporters and fellow professionals.
How do you center things vertically in CSS?
I get this one a lot. And I get this one in addition to the more general question of how to horizontally center things in CSS which I addressed in an earlier tip all about floats.
On the topic of vertical centering, some people will tell you it’s really difficult. But these days it doesn’t require much CSS and can be done on any element - even in a responsive project when you don’t know how wide or tall the container or the element to be centered is.
Take the following HTML which marks up a simple .modal
message box inside of a container:
[code language="html"]
<div class="modal">
<h2>Message title</h2>
<p>Message text lorem ipsum dolor sit amet</p>
</div>
[/code]
To absolutely center the .modal
element we can combine absolute positioning with translate.
Step one is to put the top left corner of the box right in the center of the parent container - which we can do by offsetting its top and left edges by 50% of the height and 50% of the width of the parent container:
[code language="css"]
.container {position: relative; width: 100vw; height: 100vh;}
.modal {position: absolute; top: 50%; left: 50%;}
[/code]
Step two is to bring the element back into the absolute center of the container. We need to move it back by half of its width and up by half of its height.
If we know the dimensions of the .modal
we can achieve this with some negative margin
and divide the width or height by 2 to get the required value. But if the .modal
is likely to change size (due to being sized with percentages for example) this won’t work.
Instead, using a translate transformation, we can move the element by a percentage of its existing size.
[code language="css"]
.modal {position: absolute; top: 50%; left: 50%;}
/* back by half its width, up by half its height */
transform: translate(-50%, -50%);
[/code]
And there you have it, the element is perfectly centered even with a variable size.
Continue reading %AtoZ CSS Quick Tip: Solving Common CSS Problems%
by Guy Routledge via SitePoint
No comments:
Post a Comment