JQuery Mobile Button - 绝对位置从中心?

时间:2015-10-29 14:16:27

标签: html css jquery-mobile

我试图在JQuery Mobile中创建一些东西,但是我需要能够从中心定位一个按钮。现在,按钮位于左上角,因此如果我调整窗口大小,一切都非常偏离中心。

<body>
    <button>Button</button>
    <div />
</body>

div {
position: absolute;
width: 200px;
height: 200px;
background-color: black;
}

button {
position: absolute;
top: 200px;
left: 200px;
}

小提琴:http://jsfiddle.net/chpt3x1v/4/ 我无法让JQM在JSFiddle中工作(如果没有显示大量错误,我也不知道如何),所以我只使用常规按钮,但同样的前提适用。

两个图像: Without Ripple enabled With Ripple enabled 如你所见,它完全偏离中心。

2 个答案:

答案 0 :(得分:1)

首先,您的代码没有开始标记。其次,您需要将父元素(即div)定位为相对。

第三,您已使用相同的尺寸将按钮定位到div的最边缘。尝试:

<body>
    <div>
    <button>Button</button>
    <div />
</body>

div {
position: relative;
width: 200px;
height: 200px;
background-color: black;
}

button {
position: absolute;
top: 50%;
left: 50%;
z-index: 1;
}

z-index属性将允许按钮覆盖div。

答案 1 :(得分:1)

更新的答案:

您需要为按钮设置一个宽度和高度,然后将上边距设置为负高度的一半,将左边距设置为负宽度的一半:

  

更新了 DEMO

<div class="thediv"></div>        
<button data-role="none" class="theButton">Button</button>

.thediv {
    position: absolute;
    width: 200px;
    height: 200px;
    background-color: black;
}

.theButton {
  position: fixed; /* or absolute */
  top: 200px;
  left: 200px;
  width: 80px;
  height: 80px;
  margin-top: -40px;
  margin-left: -40px;
}

原始回答:

您可以使用固定定位和负边距来保持居中:

<div data-role="page" id="page1">
    <div role="main" class="ui-content">
        <div class="centered"><button>Button</button></div>
    </div> 
</div>  

.centered {
  position: fixed; /* or absolute */
  top: 50%;
  left: 50%;
  background-color: black;
  width: 200px;
  height: 200px;
  margin-top: -100px;
  margin-left: -100px;
}

.centered button {
    margin: 0 !important;
    height: 100%;
}
  

更新了 FIDDLE

相关问题