请问大家 在设置绝对定位百分百的时候,是怎样空出左右两边边距的?

作者站长头像
站长
· 阅读数 9

请问大家 在设置绝对定位百分百的时候,是怎样空出左右两边边距的?

这时候margin 是做不到,这是我的处理方法,请问还有更好的方法吗?

回复
1个回答
avatar
test
2024-06-30

很简单啊。

1. 固定间距的情况 position:aboslute + left:10px;right:10px 然后 width:auto 就好了。

<div class="box"></div>
<style>
.box {
  width: auto;
  height: 40px;
  background: #f00;
  position: absolute;
  left: 20px;
  right: 20px;
  bottom: 0;
}
</style>

2. 固定宽度的情况 position:absolute + left:0;right:0 然后 width:80vw 搭配 margin:0 auto 就行了。

<div class="box"></div>
<style>
.box {
  width: 80vw;
  height: 40px;
  background: #f00;
  margin: 0 auto;
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
}
</style>

👉 在线Demo

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容