至于控件右侧的间距,您的#gui
元素的右边距为 15px,因此您可以通过添加margin-right:0;
以下 CSS 规则来纠正此问题#gui
:
#gui {position: absolute; top: 0; right: 0; margin-right:0;}
至于对齐要居中的元素,我在这里对其进行了分解:
理论
为了使之类的东西居中div
,使用 CSS 的方法是让子元素使用margin-right
并且margin-left
都设置为auto
,并且父元素需要足够宽以填充您希望容器居中的区域区域。
解决方案
容器的宽度(在这种情况下#buttons
)仅与其中的按钮一样宽,因此如果您只是这样做,按钮的宽度不足以使按钮居中:
#button {
margin-left: auto;
margin-right: auto;
}
因此,必须增加宽度#buttons
容器,使其与您需要的一样宽,在这种情况下,与#gui
元素一样宽,但是这样做仍然不会让按钮居中,因为有其中两个,因此您需要一个包装器元素,该元素在内部为按钮居中创建空间。这在 DOM 中看起来像这样:
<div id="buttons-wrapper">
<div id="buttons">
<button type="button" id="startButtonId" class="btn btn-primary" tabindex="13">Start Animation</button>
<button type="button" id="resetButtonId" class="btn btn-default" tabindex="14">Reset</button>
</div>
</div>
然后#buttons-wrapper
需要设置为#gui
(按钮应该居中的空间的目标宽度)的宽度,并且#buttons
需要设置为等于子容器#startButtonId
和之和的宽度#resetButtonId
,然后margin-right
和margin-left
最后可以应用于#buttons
,它将按预期工作。
要动态设置宽度,您必须使用 JavaScript 并测量所需容器的宽度:
document.getElementById('buttons-wrapper').style.width = gui.width + 'px';
target_width = 5; // a couple pixels extra
target_width = target_width + document.getElementById('startButtonId').offsetWidth;
target_width = target_width + document.getElementById('resetButtonId').offsetWidth;
document.getElementById('buttons').style.width = target_width + 'px';
我已将针对您的特定案例的完整解决方案放入此小提琴中:http: //jsfiddle.net/bnbst5sc/4/

通用解决方案
作为一般情况,它在您的解决方案的上下文之外:
#outer-wrapper {
position: absolute;
top: 100px;
left: 150px;
width: 300px;
padding: 10px 0;
background-color: #ff0000;
}
#inner-wrapper {
margin-left: auto;
margin-right: auto;
width: 175px;
padding: 10px 0;
background-color: #00ff00;
}
button {
display: inline-block;
float: left;
}
#btn1 {
background-color: #f0f000;
width: 100px;
}
#btn2 {
background-color: #00f0f0;
width: 75px;
}
<div id="outer-wrapper">
<!-- #outer-wrapper, has an arbitrary width -->
<div id="inner-wrapper">
<!-- #inner-wrapper, as wide as the sum of the widths of #btn1 and #btn2 and has margin-left and margin-right set to auto-->
<button id="btn1">Button 1</button>
<button id="btn2">Button 2</button>
</div>
</div>