在相对父容器中将绝对按钮居中的正确方法

Pay*_*tte 2 html css css-position twitter-bootstrap-3

我已经达到了我想要的结果。但这不是正确的方法。例如,如果我的父容器改变了宽度,这个 hack 将不起作用。但是,我这样做只是为了将其显示在屏幕上,以尝试在浏览器中以正确的方式解决问题。

在此处查看屏幕截图

HTML

<div class="container">
                <div class="row">
                    <div class="col-md-4">
                        <div class="product-wrapper">
                            <div class="product-card">
                                <a href="lathes-single.html" class="product-img-wrapper"><img src="../assets/img/46-455.jpg" alt=""></a>
                                <h4> 46-460 12 1/2 in. Variable Speed MIDI-LATHE® </h4>
                                <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.</p>
                                <a href="lathes-single.html" class="btn btn-lg btn-primary">View Product</a>
                            </div>
                        </div>
                    </div>
                </div>
</div>
Run Code Online (Sandbox Code Playgroud)

对不起,我古怪的间距。出于某种原因,从 Sublime Text 3 中粘贴出来的东西,一旦来到这里,一切都会被顶起来。

相关 CSS

.product-img-wrapper {
   text-align: center;
}

.product-img-wrapper img {
    width: 200px;
    height: 200px;
}

.product-wrapper {
    position: relative;
    margin: 50px 0;
}

.product-card {
    position: relative;
    max-width: 330px;
    height: 450px;
    border: 1px solid #eee;
    margin: 25px auto 0 auto;
    text-align: center;
    padding-left: 20px;
    padding-right: 20px;
    box-shadow: 7px 7px 5px #838485;
 }

.product-card .btn {
    position: absolute;
    min-width: 200px;
    bottom: 15px;
    left: 60px;
 }
Run Code Online (Sandbox Code Playgroud)

小智 5

在您的 .btn 上使用它。这将使您的 btn 水平居中。 css3:translateX 水平居中元素

left: 50%;
 -webkit-transform: translateX(-50%);
 -moz-transform: translateX(-50%);
 transform: translateX(-50%);
Run Code Online (Sandbox Code Playgroud)

  • 我宁愿不使用另一个 hack 来解决这个问题。CSS 转换不应该是解决定位问题的方法。即使它确实达到了结果。感谢您的投入! (2认同)