I am making a website and I\'m trying to vertically center:
position: absolute;
width:1200px;
height:600px;
top: 50%;
left: 50%;
margin-left: -600px;
To answer your question why top: 50%
is not working, when you use property top
on an element, the parent of that element needs to have a static height set in place. This should be in px
or a unit other than percent. If you really need to use percent in your parent as well, then you can move on to the next parent (which is the parent of that parent) and have that one a fixed static height.
To vertically centering anything. I prefer to use this method
The use of CSS transform
since you don't have to know what the width of height your element has.
position: relative;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
Don't forget to add browser/vendor prefixes.
You can refer here for vendor prefixes.
If you don't know the height of your parent. You have two options:
$('.parent').height( $(this).height() );
.parent {
/* Unkown height */
}
.child {
/* Create columns */
width: 50%;
float: left;
}
.child-1 {
position: relative;
top: 50%;
text-align: center;
-webkit-transform: translateY(-50%);
-moz-transform: translateY(-50%);
-ms-transform: translateY(-50%);
-o-transform: translateY(-50%);
transform: translateY(-50%);
}
Lorem ipsum
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Tip: If you are taking responsive into concern, just set height again in JavaScript on browser resize. You can get the new natural height by setting height to auto in JavaScript and do the process again.
display: table
instead. CSS-Tricks has a very good example here.