Alfred
Alfred

Reputation: 21406

How to make the div stick to top, on the same time center of page?

I have a div with fixed height and width, that I centered using margin left and right auto. But I want this bar visible throughout my page, so that I glued it using position:absolute. But then the bar comes to left and is not centered anymore. How can I pin the bar to center top position?

<div class="bar">bar</div>

.bar{
    width: 400px;
    height: 40px;
    margin-left:auto;
    margin-right:auto;
    background-color:orange;
}

Here is the fiddle.

Upvotes: 0

Views: 2859

Answers (7)

Karthik Naidu
Karthik Naidu

Reputation: 141

You can handle this using jquery by dynamically changing the left value of the div, below is the code -

$(document).ready(function(){
   $('.bar').css('left',($(document).width() - $('.bar').width())/2);
});

Or if you want to do it with css - add the below css properties

.bar{
 left : 50%;
 margin-left:-200px;//should be half in the width of the div
}

Upvotes: 0

LcSalazar
LcSalazar

Reputation: 16841

So the bar will remain in top, even if you scroll the page, you have to use position:fixed. Then, to center it, set the left to 50%, and the margin-left to minus the half of the width.

.bar{
    width: 400px;
    height: 40px;
    position: fixed;
    top: 10px;
    left: 50%;
    margin-left: -200px;
    background-color:orange;
}

http://jsfiddle.net/hkZju/9/

Upvotes: 0

Duncubuntu
Duncubuntu

Reputation: 130

I think adding either:

position: fixed top right;

Like TylerH said, or

position:absolute top right;

Would be your best options. More flexible.

Fixed to always show, Absolute to "pin" to page.

Upvotes: 0

sinisake
sinisake

Reputation: 11328

http://jsfiddle.net/hkZju/12/

.bar{
    width: 400px;
    height: 40px;
    top:0;
    left:50%;
   margin-left:-200px;
    background-color:orange;
    position:fixed;
}

Upvotes: 2

Javad
Javad

Reputation: 4397

What you need is to put the .bar inside a div which has position: absolute and width: 100%

Check this fiddle demo

.bar{
   position: absolute;
   width: 100%;
}

.bar div {
   width: 400px;
   height: 40px;
   margin-left:auto;
   margin-right:auto;
   background-color:orange;    
}

Upvotes: 0

Ford Filer
Ford Filer

Reputation: 325

Try using a 100% width container div, fixing that to the top, and then putting your bar centered inside it. CSS:

.bar{
    width: 400px;
    height: 40px;
    margin:0 auto;
    background-color:orange;
}
.container
{
width:100%;
    position:fixed;
    top:0px;
    left:0px;
}

Updated Fiddle

Upvotes: 2

MegaMind
MegaMind

Reputation: 671

.bar{
width: 400px;
height: 40px;
left : 50%;
margin-left:-200px;
top : 0%;
position : absolute;
background-color:orange;
}

Upvotes: 0

Related Questions