0

I can't quite get to the bottom of this: it seems that my parent div is being ignored by the browser when I want to align it. Hopefully any of you guys can get it! Thanks!

This is my parent div:

#button-subheading {
height: auto;
width: auto;
text-align: center;
margin-left: auto;
margin-right: auto;
}

and this is my child:

 .button, button {
    color: #fff !important;
    font-size: -63px;
    font-family: "CentraleSans-Bold","Helvetica Neue",Helvetica,Arial;
    line-height: 265%;
    text-decoration: none;
    background-color: #167de4;
    padding: 0 20px;
    position: absolute;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    -ms-border-radius: 3px;
    -o-border-radius: 3px;
    border-radius: 3px;
    -webkit-background-clip: padding;
    -moz-background-clip: padding;
    border: 1px solid #1d4ea4;
    -moz-box-shadow: 0 1px 1px rgba(0,0,0,0.23),inset 0 1px 0 rgba(255,255,255,0.19);
    background-image: -webkit-gradient(linear, 50% 100%, 50% 0%, color-stop(0%, #3669ef), color-stop(100%, #4f95f4));
    background-image: -webkit-linear-gradient(bottom, #3669ef 0%,#4f95f4 100%);
    background-image: -moz-linear-gradient(bottom, #3669ef 0%,#4f95f4 100%);
    background-image: -o-linear-gradient(bottom, #3669ef 0%,#4f95f4 100%);
    background-image: linear-gradient(bottom, #3669ef 0%,#4f95f4 100%);
    text-shadow: 0 1px 2px rgba(0,0,0,0.75);
    white-space: nowrap;
    text-overflow: ellipsis;
    }

when I try to implement it trough this HTML it gets stuck on the left of the screen:

    <div id="button-subheading">
        <div class="button" href="#" style="opacity: 1;">Get started with a free 30-day trial</div>
    </div>
4

3 回答 3

3

如果您只想将该元素放置在中心,这可能是一种方法:

#button-subheading {
  position: absolute;
  left: 50%;
  top: 50%;
  height: auto;
  width: auto;
  text-align: center;
  margin-left: -150px; /* half the width of your element */
  margin-top: -150px;  /* half the height of your element */
}

小提琴

于 2013-06-21T20:37:42.077 回答
1

这里已经有几个答案,甚至是一个选定的答案。但是我想无论如何我都会分享我的替代解决方案,因此您可以使用更多选择。

我解决的方法是更改​​.button下的一行CSS,按钮样式,position:absolute转向display:inline-block. 绝对定位可能很难在布局中正常工作,因为它基本上会从 HTML 的“流”中删除元素。

另外,我认为可能对您有帮助的另一件小事是对按钮使用锚 (a) 元素,而不是 div,因为单击锚实际上会将您带到指定的 href。

这是一个 JSfiddle:http: //jsfiddle.net/RgGHW/

无论如何,很高兴您的问题得到了答案!

于 2013-06-21T20:54:07.593 回答
0

绝对定位可能有点烦人,我假设你有一个像素宽度的容器 div。只需在容器 ( button-sub heading) 上设置宽度,然后在button. 该按钮将在其容器中居中。

您必须在要居中的元素上设置宽度margin:auto

这是粗略的例子:http: //jsfiddle.net/hppXY/4/

于 2013-06-21T20:46:49.267 回答