Skip to content Skip to sidebar Skip to footer

How Do I Automatically Center A Fixed Element?

I'm currently attempting to keep my header menu fixed at the top of the screen, even when scrolling. The issue is that whenever I set the position to fixed, it loses it's centerin

Solution 1:

Try giving it a left:50%; and a margin-left which is minus half the width.

left: 50%;
margin-left: -200px;

Updated fiddle:

http://jsfiddle.net/x3vh99vg/1/

A better way (suggested by zgood in a comment below), which does not use hardcoded margins is to translate the element on the x-axis by 50%;

transform:translateX(-50%);

Fiddle:

http://jsfiddle.net/x3vh99vg/2/


Solution 2:

You need to add:

#top_header {
    top: 0;
    left: 0;
    right: 0;
    width: YOUR WIDTH;
    margin: 0 auto;
}

http://jsfiddle.net/5gLz8zur/


Solution 3:

You could wrap you header content in a div and then give your header a style of display:flex along with position:fixed.

See this fiddle.

HTML:

<header>
    <div id="top_header">
        <p id="centering_example">centering help</p>
        <a id="SELECTED" class="button" href="index.html">Home</a>
        <a class="button">Games</a>
        <a class="button">About us</a>
        <a class="button">Blog</a>
    </div>
</header>

CSS:

header{
    position: fixed;
    width:100%;
    display: flex;
    justify-content: center;
}

Post a Comment for "How Do I Automatically Center A Fixed Element?"