Reputation: 65
I need the div to be in the center of the page at all times whether user resizes webpage or not.
I have tried using: margin: auto; margin: 0 auto; margin-left: auto; margin-right auto;
but neither of those three worked.
HTML:
<div id="grayinnerbackground">
</div>
CSS:
div#grayinnerbackground {
margin: auto;
width:1000px;
background-color: #D9D9D9;
height: 100%;
position: fixed;
z-index: -1;
}
Here is a fiddle for an example of what I'm talking about. http://jsfiddle.net/ymvDJ/
Thanks.
Upvotes: 0
Views: 77
Reputation: 390
Remove position: fixed
, change the width
to 50px
and make sure you have a 0
before auto
in margin: auto
.
Update:
To have the div be as high as the window, be sure to set the body
and html
to height: 100%;
too:
body, html {
height: 100%:
}
Upvotes: 0
Reputation:
If you do want the position to be fixed, add these rules and drop the usual margin trick:
left: 50%;
margin-left: -25px; // half the width of your element
See it here: http://jsfiddle.net/8DfnG/2/
Upvotes: 1
Reputation: 16723
This this HTML:
<div id="grayinnerbackground">
foo
</div>
CSS:
div#grayinnerbackground {
margin: auto;
width: 50px;
background-color: #ccc;
height: 100%;
}
I'm not entirely sure why it didn't work until I put text into the div, checking something now.
UPDATE
Sigh, ok, i'm tired. If the div is empty, and you have a height of 100%, it is going to be 100% the height of its parent, the <body>
in this case. Since there is no other content, the <body>
has a height of 0. Give the <div>
an absolute height, and it will pop in:
div#grayinnerbackground {
margin: auto;
width: 50px;
background-color: #ccc;
height: 10px;
}
Upvotes: 0
Reputation: 694
You can try this
div#grayinnerbackground {
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
width: 50px;
background-color: #D9D9D9;
height: 100%;
}
More about the working here: http://codepen.io/shshaw/full/gEiDt
Upvotes: 0
Reputation: 574
Use:
position: relative
If that still doesn't work you may need to add this as well:
display: block;
"position: fixed" means that no matter what it stays at a x and y coordinate.
Upvotes: 0
Reputation: 288020
You can use
position: fixed;
left: 50%;
width: 50px;
margin-left: -25px; /* width ÷ 2 */
Demo: http://jsfiddle.net/ymvDJ/3/
Upvotes: 0