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

时间:2020-07-10 22:31:52

标签: html css centering

我需要网站上的导航栏在具有position: fixed;属性的同时保持页面水平居中,并且宽度必须始终与div中的内容相同

有没有办法做到这一点?

这是我现在拥有的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;
}

这里是my website,如果您需要查看我的需要的话。

3 个答案:

答案 0 :(得分:1)

删除代码中的margin-left

transformleft设置为水平居中。

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

答案 1 :(得分:0)

在标签周围添加包装器

<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>

答案 2 :(得分:0)

另一种选择是在元素周围添加一个flexbox包装器并固定其位置:

.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>

添加了边框以提高视觉清晰度。