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

image.png

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

阅读 2.9k
6 个回答

很简单啊。

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

设置widht的前提下
left:0;
right:0;
margin:auto;

我一般在按钮外面再套一层:

  <div class="bottom">
    <div class="button">按钮</div>
  </div>

    .bottom{
      position:absolute;
      bottom:0;
      width:100%;
      padding:0 100px;
      box-sizing:border-box;
    }
    
    .button{
      width:100%;
      height:20px;
      background-color: blue;
      text-align:center;
    }

利用box-sizing把左右两边距离留出来,这样按钮的样式就可以相对独立些,放在其它地方也是可以的。

新手上路,请多包涵
  1. 增加父级容器,添加padding: 0 10px
  2. 定位可以直接left: 10px; right: 10px,无需设置宽度;

给外面套个div,这个div绝对定位,宽100%,然后里面再用div去相对定位不就行了?

position: absolute;
bottom:0;
left:50%;
width: 730px;
transform: translateX(-50%);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题