DuckN'Bear
DuckN'Bear

Reputation: 385

How to horizontally center an always-on-top (sticky) element with css3?

I need to achieve what's on the image. I can't put my menu in the blue area (horizontal center + vertical top + sticky)

Tried using position:fixed but this was the best I could get.

My problem

CSS:

.menu 
{   
position:fixed;
height: 40px;
width: 505px;

background: #4c4e5a;
background: -webkit-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
background: -moz-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
background: -o-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
background: -ms-linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);
background: linear-gradient(top, #4c4e5a 0%,#2c2d33 100%);

-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}

Thanks in advance.

Upvotes: 0

Views: 9096

Answers (2)

Vladimir Evstratov
Vladimir Evstratov

Reputation: 11

You should set left to 50% and then add transform property:

.menu {
  position:fixed;
  width: 505px;
  left: 50%;
  transform: translateX(-50%);
}
 

Upvotes: 1

Joseph Silber
Joseph Silber

Reputation: 220066

The trick is to set left to 50%, then pull it back with a negative margin-left equivalent to half the element's width:

.menu {   
    position:fixed;
    width: 505px;
    top: 0; left: 50%;
    margin-left: -252px; /* 505 / 2 */
}

Here's the fiddle: http://jsfiddle.net/heXR7/

Upvotes: 3

Related Questions