View Full Version : Css center div
keyboard
03-02-2012, 05:32 AM
Hello everyone,
I'm sure there is a very simple answer to my question, but I just can't work it out.
How do you center a div?
It's that simple. Currently I'm using margin-left:29%; but this won't center it if there screen is bigger or smaller.
Yes I've googled it, no I can't find an answer.
Any help?
ankush
03-02-2012, 06:06 AM
try this
margin:auto;
keyboard
03-02-2012, 10:05 PM
Thanks for your reply,
It still won't work. Tried that but it only centers it vertically not horizontally. I'd either like it to just do horizontally or do both, preferably the latter.
I'm using this to style a div, which contains more divs including the navigation menu and the main content window.
Any help??????????
jscheuer1
03-03-2012, 01:53 AM
Tried that but it only centers it vertically not horizontally.
I think you have your horizon mixed up with your vertex/zenith line.
keyboard
03-03-2012, 06:33 AM
When I tried the marign:auto; it moved it down the page vertically but it was still right up against the left of the page.
Keyboard1333
djr33
03-03-2012, 07:08 AM
margin:auto; usually works. We'll need a link to your page to figure out why this time it is different.
keyboard
03-03-2012, 07:25 AM
Can't give you a link right now. Will post one in a couple of days.
jscheuer1
03-03-2012, 11:28 AM
It may or may not be adaptable to what you have in mind, but there's always:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Center</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
html, body {
height: 100%;
margin: 0;
}
#center {
position: absolute;
margin: 0;
top: 50%;
left: 50%;
height: auto;
width: auto;
border: 1px solid #000;
padding: 1ex;
}
</style>
<script type="text/javascript" defer>
(function(){
function center(){
var center = document.getElementById('center');
center.style.marginLeft = center.offsetWidth / -2 + 'px';
center.style.marginTop = center.offsetHeight / -2 + 'px';
}
if (window.addEventListener){
window.addEventListener('DOMContentLoaded', center, false);
}
else if (window.attachEvent){
center();
}
})();
</script>
</head>
<body>
<div id="center">Where Am I?</div>
</body>
</html>
Works in IE 6+, virtually all current version browsers. A word of caution though - if the window is narrower or shorter than the center div, part of it will be off screen to the left or top respectively, with no possibility of scrolling that part into view. And if images are used within the center div, they should have their width and height specified.
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.