如何修复HTML中按钮的位置?

时间:2019-01-19 20:39:09

标签: html css

我有两个buttons会根据页面上的事件使用JS出现/消失的<h4>标签来改变位置。当h4可见时,如何使按钮保持在原位? (比不可见时要低)。

内联CSS仅用于测试。

谢谢!

  <h4 id="greutate">Greutate: <span id="greu">20</span> kg</h4>
  <button type="button" class="btn btn-info" style="margin-right: 2%;">Inapoi Acasa</button>
  <button type="button" class="btn btn-info" style="margin-left: 2%;">Cumpara Folie</button>

2 个答案:

答案 0 :(得分:0)

您可以使用position:absolute css属性相对于position:relative父元素放置任何元素,这将是您所描述的h4button元素的包装。这样,h4的可见性将不会影响按钮的位置。

您还可以使用opacity:0隐藏h4标签,这会将其保留在相同位置,并且不会移动按钮。

答案 1 :(得分:0)

您可以切换不透明度,但是屏幕阅读器仍会读取标题。如果您担心可访问性,请在元素上使用absolute定位,然后将其包装在具有固定高度的容器中:

document.getElementById('toggle').addEventListener('click', function() {
    var el = document.getElementById('greutate');
    var current = el.style.display;

    el.style.display = current === 'none' ? 'block' : 'none';
});
.container {
  position: relative;
  height: 100px;
}

.container .btn-container {
  position: absolute;
  width: 100%;
  bottom: 0;
}

#greutate {
  position: absolute;
}
<div class="container">  
<h4 id="greutate">Greutate: <span id="greu">20</span> kg</h4>
  <div class="btn-container">
  <button type="button" class="btn btn-info" style="margin-right: 2%;">Inapoi Acasa</button>
  <button type="button" class="btn btn-info" style="margin-left: 2%;">Cumpara Folie</button>
  </div>
</div>

<button style="margin-top: 5%;" id="toggle">Toggle</button>