CSS Responsive Center Div
I wanted to do the same thing 2 years ago, there's the solution:
Because you want it responsive, you may use the @media
function in CSS3. Like this:
@media (max-width: 480px) {
#div {
top: 50%; /* IMPORTANT */
left: 50%; /* IMPORTANT */
display: block;
position: absolute;
background: url(images/background.png) no-repeat center center;
width: 750px;
height: 417px;
margin-top: -208.5px; /* HALF OF THE HEIGHT */
margin-left: -375px; /* HALF OF THE WIDTH */
}
}
The max-width
you use is the maximum width of the device screen. You just copy it and change the width, height, margin-left and margin-top
for the image. Also, you should change the background
tag!
It will center the image on the page.
You can see an exemple at: Créations MicroWeb - Carrières. The image is totally centered even if you change the window side.
You can add overflow: hidden;
on the body
to make the page unscrollable when the resolution is too low. Like I did.
EDIT: JSFiddle
You could use CSS transform:
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
Try with auto margins and display as table:
.your-class {
margin-left: auto;
margin-right: auto;
display: table;
}