Search code examples
htmlcsscentering

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.


Solution

  • 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%;
    }