以div为单位的响应式垂直对齐项目,以%为单位

时间:2017-01-17 07:51:55

标签: html css

我正在尝试对齐垂直所有div,如图中所示。到目前为止,我的所有内容都有边距和填充,以%为准。但我认为这是一个古老的学校,也许可以用其他方法完成。

enter image description here

显示表,table-cell,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>

1 个答案:

答案 0 :(得分:0)

您使用这种解决方案是否正确?
(请参阅代码段中的一些评论)

/* 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>

我希望它能以任何方式帮助。