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:
Solution 2:
You need to add:
#top_header {
top: 0;
left: 0;
right: 0;
width: YOUR WIDTH;
margin: 0 auto;
}
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><divid="top_header"><pid="centering_example">centering help</p><aid="SELECTED"class="button"href="index.html">Home</a><aclass="button">Games</a><aclass="button">About us</a><aclass="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?"