How to do Vertical+Horizontal centering in CSS - css

It regularly occurs that I want to center a css box inside another one both vertically and horizontally. What's the simplest way to do so that satisfies the following constraints?
The box should be precisely centered, not approximately.
The technique should work in modern browsers and in IE versions back to 8
The technique should not depend on explicitly knowing the width or height of either the centered content or the containing box.
I generally know the container is larger than the content, but supporting larger content (which then overflows symmetrically) would be nice...
The underlying content of the container must still be able to respond to clicks and hovers except where obscured by the centered content
I currently use 4 (!) nested divs to achieve this, with css along the following lines:
.centering-1 {
position:absolute;
top:0; left:0; right:0; bottom:0;
text-align:center;
visibility:hidden;
}
.centering-2 {
height:100%;
display:inline-table;
}
.centering-3 {
display:table-cell;
vertical-align:middle;
}
.centering-content {
visibility:visible;
}
You can see this in action as a jsbin snippet.
However, this approach, while workable, feels like extreme overkill due to the large number of wrapper divs, and it doesn't work with content that's larger than the container. How can I center things in CSS?

Horizontal centering is easy:
.inner {
width: 70%; /* Anything less than 100% */
margin-left: auto;
margin-right: auto;
}
But vertical centering is a little tricky. The best technique for modern browsers is to combine inline-block and a pseudo elements. This originates from "Ghost element", the last technique at http://css-tricks.com/centering-in-the-unknown/. It sets adds a pseudo-element and uses inline-block styles get the centering.
The CSS:
.outer {
height: 10rem;
text-align: center;
outline: dotted black 1px;
}
.outer:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
.inner {
width: 10rem;
display: inline-block;
vertical-align: middle;
outline: solid black 1px;
}
An example on Codepen: http://codepen.io/KatieK2/pen/ucwgi
For simpler cases, the following may be good options:
For single lines of content, you can do a quick and dirty vertical centering job on the text within an element by using line-height larger than your font-size:
.inner {
border: 1px solid #666;
line-height: 200%;
}
The solution with widest support is to use a non-semantic table. This works with very old versions of IE and doesn't require JavaScript:
td.inner {
vertical-align: middle;
}
And here is simple solution for known height elements (which could be in ems, not px):
.outer {
position:relative;
}
.inner {
position: absolute;
top:50%;
height:4em;
margin-top:-2em;
width: 50%; left: 25%;
}

You can get by with 2 fewer elements. Anything less than this is going to require things that IE8 (and IE9) doesn't support.
http://cssdeck.com/labs/0ltap96z
<div class="centering-1">
<div class="centering-2">
<div class="intrinsically-sized-box">
<p>You can put any content here too and the box will auto-size.</p>
</div>
</div>
</div>
CSS:
body {max-width:750px;}
.generalblock {
margin-top:2em;
position:relative;
padding:10px;
border:20px solid cyan;
font-size: 18px;
}
.centering-1 {
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
text-align:center;
visibility:hidden;
display: table;
width: 100%;
}
.centering-2 {
display:table-cell;
vertical-align:middle;
}
.intrinsically-sized-box {
visibility:visible;
max-width:300px;
margin: 0 auto;
background: yellow;
position:relative;
border:1px solid black;
}

Related

CSS: Centering elements vertically

I'm trying to develop my first responsive website but I'm having some trouble (of course).
I need an element (sort of a menu) to contain 4 row of elements and each element has an image to the left and some text to the right. Now, the issue I'm having is that I can't seem to be able to make the elements center vertically correctly. I've tried several methods that seem to work for a lot of people so I thought I'ld ask if anybody knows why nothing seems to work for me.
This is what the image CSS looks like:
.tablaBuscadorElementos > img {
position: relative;
width: 20px;
height:20px;
left:0;
right:0;
top:0;
bottom:0;
margin:0 auto;
float:left;}
Here is the fiddle: http://jsfiddle.net/mampy3000/9JZdZ/1/
Appreciate any help!
since your elements are inline-block , you can inject an inline-block pseudo-element 100% height and vertical-align:middle it to img and span : DEMO
basicly (+ below update of your CSS):
.tablaBuscadorElementos:before {
content:'';
height:100%;
display:inline-block;
vertical-align:middle;
}
.tablaBuscadorElementos {
height:22%;/* instead min-height so value can be used for pseudo or direct child */
border: 1px solid black;
padding:0px;
width:100%;
}
.tablaBuscadorElementos > span {
font-size:20px;
width:80%;
vertical-align:middle; /* align to next inline-block element or baseline*/
border:1px solid black;
display:inline-block;/* layout*/
}
.tablaBuscadorElementos > img {
vertical-align:middle; /* align to next inline-block element or baseline*/
width: 20px;
height:20px;
}
.tablaBuscador, .tablaBuscadorElementos{
display:block;
}
.tablaBuscadorElementos:before {
content:'';
height:100%;/* calculated from 22% parent's height */
display:inline-block;/* layout*/
vertical-align:middle;/* align to next inline-block element or baseline*/
}
You can do this by adding this css to .tablaBuscador
position: fixed;
top: 50%;
margin-top:-100px; /* half of height */
More info here: How to center a table of the screen (vertically and horizontally)
The newer option would be to use calc() but you might run into browser support issues.
position: fixed;
top:calc(50% - 100px).
Here are which browsers support calc(): http://caniuse.com/#feat=calc
Your code needs a major tune-up. You are floating elements, using vertical-align on them, positioning them relatively with left, right, top, and bottom set to 0. None of these make any sense. Here's a cleaned up fiddle: http://jsfiddle.net/jL2Gz/.
And here's a tuned up code:
* {
padding: 0;
margin: 0;
}
body {
height:100%;
}
.tablaBuscador {
font-family: "Maven Pro", sans-serif;
height:200px;
width:40%;
}
.tablaBuscador > div {
border: 1px solid black;
padding: 10px 0;
}
.tablaBuscador > div > span {
font-size:20px;
width:80%;
border:1px solid black;
}
.tablaBuscador > div > img {
width: 20px;
height: 20px;
}
.tablaBuscador > div > * {
display: inline-block;
vertical-align: middle;
}

Left input takes all available space

I know this questions has already been answered before and I've read the topics :
Make div take all space left after another div
Expand div to take remaining width
Expand div to max width when floatleft is set
The magic of overflow hidden (external)
However I can't manage to implement them in my case or they simply don't seem to work as I try to have a fix width on the right and a flexible width on the left (unlike the above examples).
Here is my problem (which is fairly simple) : I have a form with a search field (left) and a span element (right). The span element has a fixed width and height. I want the input to fit the remaining left space.
form :
<div id="container">
<form>
<input type="search" />
<span class="submit"></span>
</form>
</div>
style.css :
#container {
width: 300px;
}
[type="search"] {
/* Positionning
* ------------ */
display: block;
height: 40px;
padding: 0px 10px;
vertical-align: top;
}
.submit {
/* Positionning
* ------------ */
display: block;
height: 40px;
width: 50px;
/* Styling
* ------- */
background-color: #CF0526;
}
From what I've read, I thought that a width: 100%; overflow: hidden on the input and a float: right on the span who be enough, sadly not. Here is a jsfiddle of my problem, hopefully it may help you.
EDIT: I changed the title from "left div" to "left input" as it may matter, especially since this solution does not work while it looks accurate for divs positionning.
You can try with the property calc like this:
input[type="search"] {
width: calc(100% - 40px);
margin:0;
padding:0;
height:30px;
float:left;
}
.submit {
float:left;
width: 40px;
height: 30px;
background-color: red;
}
The demo http://jsfiddle.net/SL3FB/10/ ... Maybe a problem the compatibility
Another solution using box.sizing who has more compatibility: http://jsfiddle.net/SL3FB/18/
You can substract the width from the span to the width from the textfield which is 100%.
Here is the fiddle http://jsfiddle.net/SL3FB/15/.
Code is like this:
width:calc(100% - 50px);
float:left;
Make 'em both float:left; to have a better result!
Hope this works for you.
Use CSS Tables
1) Set display: table-cell for both the input and the span
2) Set a fixed width on the span and (the trick:) width:100% on the input
FIDDLE
#container {
width: 300px;
border: 1px solid black;
}
form
{
display:table;
width: 100%;
}
.submit {
display:table-cell;
width: 40px;
height: 30px;
background-color: red;
}
input
{
width: 100%;
display:table-cell;
}
Does this work for you?
http://jsfiddle.net/SL3FB/4/
I've given your search a width of 85% so it fits up agains the red box.
.search {
width:85%;
}

Div keeps moving down the page when opened on different computers

Okay so this is quite hard to explain but basically I position the title div perfectly so that it is centered in the header div.
It remains in this position on some computers.
However, on other computers it jumps further down the page - even with the same positioning attributes. (This is tested on the same web browser.)
I have tried with absolute, relative etc. positioning, still no luck!
Note: This div contains text.
CSS:
#header {
position:relative;
height:170px;
background-color: #30A7BF;
margin:0px auto;
padding: 1px;
}
#title {
position: relative;
top: -20px;
left: 315px;
}
Thanks!
Hi is difficult to understand exactly your issue but I can give you a few tips to have a nice center vertical and horizontal:
For horizontal alignment you can use display:inline-block if you want all the div centered:
#header {
text-align:center;
}
#title {
display:inline-block;
}
For vertical align use line-height equal to the total height
#header {
line-height:170px;
}
This only work for one line text if you want another option tell me
And the demo here http://jsfiddle.net/8JLzy/7/
Edit
To work with a text of more than one line you can do this : First your html add a wrapper inside #title:
<div id="header">
<div id="title">
<div class="center">Your Title</div>
</div>
</div>
And on the CSS work with display property:
#title {
display:table;
height:100%;
margin:auto; /*Make the horizontal*/
}
#title .center {
display:table-cell;
vertical-align:middle;/*Make the Vertical*/
}
New demo http://jsfiddle.net/8JLzy/16/
use line-height, not position:relative
#header {
/*position:relative;*/
height:170px;
background-color: #30A7BF;
margin:0px auto;
padding: 1px;
font-size:1em;
}
#title {
line-height:0.5em; /* for example, or instead use padding-top: */
padding-left: 315px;
}

vertical alignment of image inside a div

I want to set vertical alignment of image inside a div. I use img { vertical-align:middle}
but it is not working.
Using the line-height property will solve the problem:
<style>
.someclass {
width: 300px;
height: 300px;
text-align: center;
line-height: 300px;
border: dotted;
}
.someclass img {
margin: auto;
vertical-align: middle;
}
</style>
<div class="someclass">
<img src="someimg.jpg" border="0" alt="">
</div>
This is a solution that doesn't require JavaScript (as my previous solution did).
You can achieve what you want by assigning display: table-cell to the containing div. Here's an example: http://jsbin.com/evuqo5/2/edit
I feel I must warn you that you will need to test this in every browser you intend to support. Support for the table-cell value is fairly new, particularly in Firefox. I know it works in Firefox 4, but I don't know about any of the 3.x iterations. You'll also want to test in IE (I've only tested in Chrome 10 and Firefox 4).
The CSS:
div#container {
width: 700px;
height: 400px;
position: relative;
border: 1px solid #000;
display: table-cell;
vertical-align: middle;
}
div#container img {
margin: 0 auto;
display: block;
}
You won't need the div#container img styles if you don't also want to horizontally align the image.
If you're trying to do what I think, vertical align isn't going to work; you'll need to use positioning.
In general, position the container relative, and then position the image absolute, with top and left set to 50%, and then move the image back to the center by setting negative margins equal to half the width / height.
Here's a working example: http://jsbin.com/evuqo5/edit
Basic CSS is this:
#container { position: relative; }
#container img {
position: absolute;
left: 50%;
top: 50%;
margin-top: /* -1/2 the height of the image */
margin-left: /* -1/2 the width of the image */
}
See this awser: How to vertical align image inside div
If you want to align horizontally also, add the right and left, like this:
div {
position:relative;
}
img {
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
}
The following post has some useful references:
Text Alignment w/ IE9 in Standards-Mode
Also, depending on which version of IE you are testing against, you may end up needing some browser-specific hacks or some jQuery/JavaScript code.
If you have to, use a one-row-one-cell table and take advantage of the vertical-align property. This is brute-force, not overly semantic, but it works.
If you set the div display attribute to table-cell then vertical-align: middle; will work.
The vertical-align rule only affects table cells or elements with display: table-cell.
See this article from SitePoint for a detailed explanation.
<style>
/* change body to .someClasses's parent */
body {
width: 100%;
height:  100%;
display: table;
}
body > .someclass {
width: 300px;
height: 300px;
text-align: center;
border:dotted;
margin: 0 auto
display: table-cell;
vertical-align: middle;
}
</style>
<body>
<div class="someclass">
<img src="someimg.jpg" border="0" alt="">
</div>
</body>

How to vertically center content with variable height within a div?

What is the best way to vertically center the content of a div when the height of the content is variable. In my particular case, the height of the container div is fixed, but it would be great if there were a solution that would work in cases where the container has a variable height as well. Also, I would love a solution with no, or very little use of CSS hacks and/or non-semantic markup.
Just add
position: relative;
top: 50%;
transform: translateY(-50%);
to the inner div.
What it does is moving the inner div's top border to the half height of the outer div (top: 50%;) and then the inner div up by half its height (transform: translateY(-50%)). This will work with position: absolute or relative.
Keep in mind that transform and translate have vendor prefixes which are not included for simplicity.
Codepen: http://codepen.io/anon/pen/ZYprdb
This seems to be the best solution I’ve found to this problem, as long as your browser supports the ::before pseudo element: CSS-Tricks: Centering in the Unknown.
It doesn’t require any extra markup and seems to work extremely well. I couldn’t use the display: table method because table elements don’t obey the max-height property.
.block {
height: 300px;
text-align: center;
background: #c0c0c0;
border: #a0a0a0 solid 1px;
margin: 20px;
}
.block::before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em; /* Adjusts for spacing */
/* For visualization
background: #808080; width: 5px;
*/
}
.centered {
display: inline-block;
vertical-align: middle;
width: 300px;
padding: 10px 15px;
border: #a0a0a0 solid 1px;
background: #f5f5f5;
}
<div class="block">
<div class="centered">
<h1>Some text</h1>
<p>But he stole up to us again, and suddenly clapping his hand on my
shoulder, said—"Did ye see anything looking like men going
towards that ship a while ago?"</p>
</div>
</div>
This is something I have needed to do many times and a consistent solution still requires you add a little non-semantic markup and some browser specific hacks. When we get browser support for css 3 you'll get your vertical centering without sinning.
For a better explanation of the technique you can look the article I adapted it from, but basically it involves adding an extra element and applying different styles in IE and browsers that support position:table\table-cell on non-table elements.
<div class="valign-outer">
<div class="valign-middle">
<div class="valign-inner">
Excuse me. What did you sleep in your clothes again last night. Really. You're gonna be in the car with her. Hey, not too early I sleep in on Saturday. Oh, McFly, your shoe's untied. Don't be so gullible, McFly. You got the place fixed up nice, McFly. I have you're car towed all the way to your house and all you've got for me is light beer. What are you looking at, butthead. Say hi to your mom for me.
</div>
</div>
</div>
<style>
/* Non-structural styling */
.valign-outer { height: 400px; border: 1px solid red; }
.valign-inner { border: 1px solid blue; }
</style>
<!--[if lte IE 7]>
<style>
/* For IE7 and earlier */
.valign-outer { position: relative; overflow: hidden; }
.valign-middle { position: absolute; top: 50%; }
.valign-inner { position: relative; top: -50% }
</style>
<![endif]-->
<!--[if gt IE 7]> -->
<style>
/* For other browsers */
.valign-outer { position: static; display: table; overflow: hidden; }
.valign-middle { position: static; display: table-cell; vertical-align: middle; width: 100%; }
</style>
There are many ways (hacks) to apply styles in specific sets of browsers. I used conditional comments but look at the article linked above to see two other techniques.
Note: There are simple ways to get vertical centering if you know some heights in advance, if you are trying to center a single line of text, or in several other cases. If you have more details then throw them in because there may be a method that doesn't require browser hacks or non-semantic markup.
Update: We are beginning to get better browser support for CSS3, bringing both flex-box and transforms as alternative methods for getting vertical centering (among other effects). See this other question for more information about modern methods, but keep in mind that browser support is still sketchy for CSS3.
you can use flex display such as below code:
.example{
background-color:red;
height:90px;
width:90px;
display:flex;
align-items:center; /*for vertically center*/
justify-content:center; /*for horizontally center*/
}
<div class="example">
<h6>Some text</h6>
</div>
Using the child selector, I've taken Fadi's incredible answer above and boiled it down to just one CSS rule that I can apply. Now all I have to do is add the contentCentered class name to elements I want to center:
.contentCentered {
text-align: center;
}
.contentCentered::before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -.25em; /* Adjusts for spacing */
}
.contentCentered > * {
display: inline-block;
vertical-align: middle;
}
<div class="contentCentered">
<div>
<h1>Some text</h1>
<p>But he stole up to us again, and suddenly clapping his hand on my
shoulder, said—"Did ye see anything looking like men going
towards that ship a while ago?"</p>
</div>
</div>
Forked CodePen: http://codepen.io/dougli/pen/Eeysg
Best result for me so far:
div to be centered:
position: absolute;
top: 50%;
transform: translateY(-50%);
margin: 0 auto;
right: 0;
left: 0;
You can use margin auto. With flex, the div seems to be centered vertically too.
body,
html {
height: 100%;
margin: 0;
}
.site {
height: 100%;
display: flex;
}
.site .box {
background: #0ff;
max-width: 20vw;
margin: auto;
}
<div class="site">
<div class="box">
<h1>blabla</h1>
<p>blabla</p>
<p>blablabla</p>
<p>lbibdfvkdlvfdks</p>
</div>
</div>
For me the best way to do this is:
.container{
position: relative;
}
.element{
position: absolute;
top: 50%;
transform: translateY(-50%);
}
The advantage is not having to make the height explicit
This is my awesome solution for a div with a dynamic (percentaged) height.
CSS
.vertical_placer{
background:red;
position:absolute;
height:43%;
width:100%;
display: table;
}
.inner_placer{
display: table-cell;
vertical-align: middle;
text-align:center;
}
.inner_placer svg{
position:relative;
color:#fff;
background:blue;
width:30%;
min-height:20px;
max-height:60px;
height:20%;
}
HTML
<div class="footer">
<div class="vertical_placer">
<div class="inner_placer">
<svg> some Text here</svg>
</div>
</div>
</div>
Try this by yourself.

Resources