html - 以 % 为单位的 div 高度中的响应式垂直对齐元素

标签 html css

我正在尝试将所有 div 垂直对齐,如图所示。到目前为止,我所有的边距和边距都以 % 表示,并且可以正常工作。但我认为这有点老派,也许可以使用另一种方法来完成。

enter image description here

显示表格、表格单元格、flex 等其他解决方案根本无济于事...

.holder {
   width:80%;
   height:30%;
   position: relative;
   margin: 0 auto;
}
.item-1 {
   position: absolute;
   z-index: 1;
   width: 20%;
   height: 20%;
   background: red;
   left: 0;
}
.item-2 {
   position: absolute;
   z-index: 2;
   width: 25%;
   height: 30%;
   background: blue;
   right:0;
}
.item-1:after, .item-2:after {
   content:'';
   display: block;
   padding-bottom: 100%;
}
.txt-holder {
   position: absolute;
   z-index: 11;
   width: 40%;
   margin: 0 auto;
   background: gold;
   left: 0;
   right: 0;
}

基本上 html 结构是这样的。

<div class="holder">
   <div class="item-1"></div>
   <div class="txt-holder">
       <h1>header title</h1>
       <p>any texts</p>
   </div>   
   <div class="item-2"></div>
</div>

最佳答案

您使用那种解决方案是否正确?
(查看代码片段中的一些评论)

/* Added body, because your .holder was 30% height of nothing as no parent had a size */

body {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  padding-top: 40px; /* Adding this offset for better visibility when the snippet isn't full-size */
}


/* Added these two classes */

.border1 { /* For better visibility of the objects */
  border: 1px solid black;
}

.center-y { /* For vertical centering, the parent element needs to be relative */
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}


/* Modified some below */

.holder {
  width: 80%;
  height: 30%;
  position: relative;
  margin: 0 auto;
}

.item-1 {
  /*position: absolute;*/
  z-index: 1;
  width: 20%;
  height: 20%;
  background: red;
  left: 0;
}

.item-2 {
  /*position: absolute;*/
  z-index: 2;
  width: 25%;
  height: 30%;
  background: blue;
  right: 0;
}


/* What the :afters are used for ? */

.item-1:after,
.item-2:after {
  content: '';
  display: block;
  padding-bottom: 100%;
}

.txt-holder {
  /* position: absolute; */
  z-index: 11;
  width: 40%;
  margin: 0 auto;
  background: gold;
  left: 0;
  right: 0;
}
<body>
  <div class="holder border1">
    <div class="item-1 center-y border1"></div>
    <div class="txt-holder center-y border1">
      <h1>header title</h1>
      <p>any texts</p>
    </div>
    <div class="item-2 center-y border1"></div>
  </div>
</body>

希望对您有所帮助。

关于html - 以 % 为单位的 div 高度中的响应式垂直对齐元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41691651/

相关文章:

jquery - 使用 JQuery 隐藏元素后如何修改左属性?

html - 移动期间在网页上进行 x 滚动

html - Svg 文本 tspan 没有按要求做

html - 超链接图像链接边界

html - 网站无法在老板的计算机/浏览器上正确呈现,但所有其他网站似乎都运行良好。帮助?

html - 手写笔:@media screen and (max-width: 425px) 阻止手写笔创建 css

jquery.Countdown 样式问题

jQuery-UI <button> 自动提交它的表单

html - 如何使 div 的边距不可点击?

javascript - 如何使我的输入元素高度动态?