简体   繁体   English

如何在宽度适合内部内容的同时将固定 div 水平居中

[英]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;我需要我网站上的导航栏在页面上保持水平居中,同时拥有position: fixed; property and I need the width to always be the same as the content inside the div属性,我需要宽度始终与 div 内的内容相同

Is there a way to accomplish this?有没有办法做到这一点?

Here is the CSS I have now:这是我现在拥有的 CSS:

 .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.这是我的网站,如果你需要它来看看我需要什么。

Remove margin-left in code.删除代码中margin-left

Set transform and left for horizontally center.transformleft设置为水平居中。

Modify width to 100%.width修改为 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 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>

Another option is to add a flexbox wrapper around your element and fix its position:另一种选择是在元素周围添加 flexbox 包装器并修复其 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.添加边框以提高视觉清晰度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM