使元素粘在顶部和中心
P粉301523298
P粉301523298 2024-03-19 17:30:43
[CSS3讨论组]

我有一个页面在水平和垂直方向上溢出视口,并且我想粘贴导航,以便它始终位于顶部并水平居中。

现在,我可以让粘性顶部工作,但居中不起作用。有人可以帮忙吗?

body {
  text-align: center;
}

#header {
  background-color: yellow;
  width: max-content;
  position: sticky;
  top: 0;
  left: 50%;
  translate: -50%
}

#container {
  background-color: black;
  color: white;
  width: 200vw;
  height: 200vh;
  display: flex;
  justify-content: center;
  align-content: center;
  flex-direction: column;
}

I am extremely large and wide

CodePen:https://codepen.io/hbchin/pen/bGjpQLJ

P粉301523298
P粉301523298

全部回复(1)
P粉064448449

与position:粘性和垂直定位不同,left: 50%不是动态定位选项;它只是设置初始位置。水平滚动条仍然会导致它移动,因此它保持“距左边缘 50%”。

要实现固定的左右位置,请在标题周围添加一个带有 position:fixed 的标题容器,在其中,标题 div 可以获得 auto 边距:

body {
  text-align: center;
  max-width:100vw;
  overflow:scroll;
}

/*added*/
#headercontainer{
  position:fixed; 
  width:100vw;
  left:0;
  top:0;
}
#header {
  background-color: yellow;
  width: max-content;
  /*left: 50%;*/ /*Removed*/
  margin:auto;/*added*/
}

#container {
  background-color: black;
  color: white;
  width: 200vw;
  height: 200vh;
  display: flex;
  justify-content: center;
  align-content: center;
  flex-direction: column;
}
I am extremely large and wide
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号