Centering
-
- Administrator
- Posts: 2535
- Joined: Thu Jun 21, 2012 5:49 pm
- Contact:
Re: Centering
You can also use display:inline-block; in combination with the above codes, such as vertical-align:middle; It's good to see there are so many ways to do this. XD I find this one to be the fastest, though my newfound love for inline blocks might have something to do with it, I've found them to be so useful for all sorts of things.
- FandomSavant
- Posts: 205
- Joined: Fri Mar 11, 2016 3:52 pm
- Location: California, USA
- Contact:
Re: Centering
The layout of http://fandomsavant.com is actually made up of divs within a centered container div.
-
- Posts: 23
- Joined: Sun May 17, 2015 9:34 pm
- Location: Philippines
- Contact:
Re: Centering
I can suggest two solutions to horizontally and vertically center an element.
One is Flexbox, like some people already mentioned above. It's a relatively new feature, so old browsers may not support it. (Additionally, make sure to prepend the necessary vendor prefixes.)
HTML
CSS
Then set the width and height of your .box.
The second one would be using the line-height and vertical-align hack.
Assuming we have the same HTML code...
CSS
The .box must have a set width and height for this to work.
As for the text inside the box, I'm seconding the padding solution suggested by Mikari.
I hope this helps!
One is Flexbox, like some people already mentioned above. It's a relatively new feature, so old browsers may not support it. (Additionally, make sure to prepend the necessary vendor prefixes.)
HTML
Code: Select all
<div class="container">
<div class="box"></div>
</div>
Code: Select all
html, body {
min-height: 100%;
}
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
The second one would be using the line-height and vertical-align hack.
Assuming we have the same HTML code...
CSS
Code: Select all
html, body {
min-height: 100%;
}
.container {
line-height: 100vh; /* 100% viewport height */
text-align: center; /* to center an inline-block */
}
.box {
display: inline-block;
line-height: 1;
vertical-align: middle;
}
As for the text inside the box, I'm seconding the padding solution suggested by Mikari.
I hope this helps!