I need to place a div
(with position:absolute;
) element in the center of my window. But I am having problems doing so, because the width is unknown.
I tried this. But it needs to be adjusted as the width is responsive.
.center {
left: 50%;
bottom:5px;
}
Any ideas?
HTML
CSS
http://jsfiddle.net/f51rptfy/
I understand this question already has a few answers, but I've never found a solution that would work in almost all classes that also makes sense and is elegant, so here's my take after tweaking a bunch:
What this does is saying give me a
top: 50%
and aleft: 50%
, then transform (create space)on both the X/Y axis to the-50%
value, in a sense "create a mirror space".As such, this creates an equal space on all the 4 points of a div, which is always a box (has 4 sides).
This will:
A simple approach that worked for me to horizontally center a block of unknown width:
A text-align property may be added to the #block ruleset to align its content independently of the alignment of the block.
This worked on recent versions of Firefox, Chrome, IE, Edge and Safari.
Responsive Solution
Here is a good solution for responsive design or unknown dimensions in general if you don't need to support IE8 and lower.
Here is a JS Fiddle
The clue is, that
left: 50%
is relative to the parent while thetranslate
transform is relative to the elements width/height.This way you have a perfectly centered element, with a flexible width on both child and parent. Bonus: this works even if the child is bigger than the parent.
You can also center it vertically with this (and again, width and height of parent and child can be totally flexible (and/or unknown)):
Keep in mind that you might need
transform
vendor prefixed as well. For example-webkit-transform: translate(-50%,-50%);