中心绝对定位div

244*_*boy 7 html css css-position

我有一个 div,里面有一个按钮:

我让按钮位置为absolute,其样式代码为:

  .buy-btn {
    text-align: center;
    position: absolute;
    bottom: 10px;

  }
Run Code Online (Sandbox Code Playgroud)

我怎样才能将它对齐到中心?我试过 add margin: 0 auto;,但它不起作用。

dev*_*kir 9

如果我理解你的问题,那么它将如下工作。

您可以通过三种方式做到这一点。

No1 - 使用位置。将宽度 100% 应用于按钮父 div 并应用如下按钮样式。

.buy-btn{
    display: inline-block;       /* Display inline block */
    text-align: center;          /* For button text center */
    position: absolute;          /* Position absolute */
    left: 50%;                   /* Move 50% from left */
    bottom: 10px;                /* Move 10px from bottom */
    transform: translateX(-50%); /* Move button Center position  */
}
Run Code Online (Sandbox Code Playgroud)

No2 - 使用父 div,将宽度 100% 应用于父 div 并从按钮中删除绝对位置。

.parentDiv {
    width: 100%;            /* for full width */
    text-align: center;     /* for child element center */
 }

.buy-btn{
    display: inline-block;       /* Display inline block */
    text-align: center;          /* For button text center */
}
Run Code Online (Sandbox Code Playgroud)

No3 - 使用边距,将宽度 100% 应用于您的父 div 并从按钮中删除绝对位置。

.parentDiv {
    width: 100%;            /* for full width */
 }

.buy-btn{
    display: inline-block;       /* Display inline block */
    text-align: center;          /* For button text center */        
    margin: 0 auto;              /* For button center */
}
Run Code Online (Sandbox Code Playgroud)


小智 6

/* Replace below css  and add position relative to its parent class*/

.buy-btn {
       text-align: center;
       position: absolute;
       bottom: 10px;
       left: 50%;
       display: inline-block;
       transform: translateX(-50%);
    }
Run Code Online (Sandbox Code Playgroud)