两个div 50%宽度为正方形

时间:2017-01-29 20:41:50

标签: html css css3

如何制作这样的两个div

  • 如果灰色区域变小,则两个div保持外观。

  • 在红色框中我可以使用box-sizing: border-box;padding: 50% 0;,但在蓝框中我需要输入文字。

enter image description here



.c {
  padding: 10px;
  background-color: gray;
  overflow: auto;
  margin: 0 0 10px 0;
}
.c1 {
  width: 300px;
}
.c2 {
  width: 200px;
}
.w {
  width: 100%;
}
.w div {
  float: left;
}
.i {
  width: 50%;
  height: 50px;
  background-color: red;
}
.t {
  width: 50%;
  height: 50px;
  background-color: blue;
}

<div class="c c1">
  <div class="w">
    <div class="i"></div>
    <div class="t"></div>
  </div>
</div>
<div class="c c2">
  <div class="w">
    <div class="i"></div>
    <div class="t"></div>
  </div>
</div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

这样的东西?

.square {
  box-sizing: border-box;
  padding: 50% 50% 0 0;
  width: 50%;
  float: left;
  position: relative;
}
.image {
  background: red;
}
.text {
  background: blue;
}
.text > div {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  text-align: center;
  color: white;
  padding: 50% 0;
  line-height: 0;
  text-transform: uppercase;
}
<div class="wrap">
  <div class="square image"></div>
  <div class="square text">
    <div>text</div>
  </div>
</div>

答案 1 :(得分:0)

您可以为每个项目50vwwidth设置相同的height来制作正方形。然后使用flexfloatinline-block,无论如何要将它们并排放置。

<强> jsFiddle

.container {
  display: flex;
}
.item {
  width: 50vw;
  height: 50vw;
}
.image {
  background: url("https://unsplash.it/800/800?random") center / cover;
}
.text {
  background-color: pink;
  
  /*center the text*/
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="container">
  <div class="item image"></div>
  <div class="item text">Text</div>
</div>

答案 2 :(得分:0)

&#13;
&#13;
.square{
    width: 50%;
    
    position: relative;
    float: left;
}
.square:before{
    content: '\0020';
    padding-top: 100%;
  
    display: block;
}
.boxer{
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}
#c1{
    background: salmon;
}
#c2{
    background: lightblue;
}
#image{
    width: 100%;
    height: 100%;
    position: relative;
}
.centered{
    position: absolute;
  
    top: 50%;
    left: 50%;
  
    text-align: center;
  
    -webkit-transform: -webkit-translate(-50%, -50%);
       -moz-transform:    -moz-translate(-50%, -50%);
            transform:         translate(-50%, -50%);
  
}
&#13;
<div id="container">
   <div class="square">
      <div class="boxer" id="c1">
          <img id="image" src="https://www.archlinux.org/static/vector_tux.864e6cdcc23e.png"/>
      </div>
   </div>
   <div class="square">
      <div class="boxer"  id="c2">
          <p class="centered">
          You can put your text here!
          I you don't like to have it centered,
          remove class centered!
          </p>
      </div>
   </div>
</div>
&#13;
&#13;
&#13;