How do I horizontally center a fixed div while having the width fit the content inside

I need the navigation bar on my website to stay horizontally centered on the page while having the position: fixed; property and I need the width to always be the same as the content inside the div

Is there a way to accomplish this?

Here is the CSS I have now:

.tab {     overflow: hidden;     background-color: #505050;     padding: 0;     width: fit-content;     border-radius: 15px;     position: fixed;     top: 0;     margin-left: 280px;     z-index: 10; }

Here is my website if you need that to see what I need.

Add Comment
3 Answer(s)

Remove margin-left in code.

Set transform and left for horizontally center.

Modify width to 100%.

.tab {     overflow: hidden;     background-color: #505050;     padding: 0;     width: 100%;     border-radius: 15px;     position: fixed;     top: 0;     z-index: 10;     transform: translateX(-50%);     left: 50%; } 
Add Comment

Add a wrapper around your tab

<div class="tabwrapper">     <div class="tab">     </div> </div>  <style> .tabwrapper {    position: fixed;    width: 100%;    text-align: center;    top: 0; }  .tab {     margin: 0 auto;     display: inline-block; } </style> 
Answered on July 16, 2020.
Add Comment

Another option is to add a flexbox wrapper around your element and fix its position:

.tab-wrapper {     display: flex;     justify-content: center;     position: fixed;     top: 0;     width: 100%;     border: solid red 1px;     overflow: hidden;     z-index: 10; }  .tab {     padding: 0;     border: solid blue 1px; }
<div class='tab-wrapper'>   <div class='tab'>     Content   </div> </div>

Borders added for visual clarity.

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.