CSS并排排列2个div

时间:2014-11-24 20:49:02

标签: html css

如果一个具有设定宽度,另一个应该自动用尽其余空间,如何将两个div彼此相邻对齐。如果帮助中省略了设置宽度div,则另一个div应调整大小以占用容器div中的所有空间。

它被用于图像/内容设计。我想要它,所以如果没有图像,内容会占用它的空间。

这是我的代码:

CSS

.sub-row-wrapper { 
    background: #f00; 
    text-align: left; 
    width: auto; 
    position:relative; 
    padding: 12px; 
    margin-bottom: 12px; 
    border-bottom: 1px; 
    border-style: solid; 
    border-color: #ccc; 
} 

.sub-row-left-col { 
    background: #ff0; 
    display:inline-block; 
    width: 25%;
   text-align: left; 
}

.sub-row-right-col { 
    background: #f0f; 
    display:inline-block; 
    width: auto;  
}

HTML

<div class="sub-row-wrapper">

    <div class="sub-row-left-col">
        <p>Left img</p>
    </div>

    <div class="sub-row-right-col">
        <p>This should be positioned right of 'left img' and should not go underneath the left img</p>
    </div>
</div>

我有以下代码

http://jsfiddle.net/fr9zvaj3/

我想要的第一个div是黄色框位于紫色框的左侧。黄色框应该是25%宽,紫色框应该用尽任何空间。

当我取下黄色方框时,紫色方框应自动全宽(就像第2行一样)

2 个答案:

答案 0 :(得分:2)

一种解决方案是将display: flex用于容器并将width: 100%设置为紫色div:

.sub-row-wrapper {
  background: #f00;
  text-align: left;
  width: auto;
  position: relative;
  padding: 12px;
  margin-bottom: 12px;
  border-bottom: 1px;
  border-style: solid;
  border-color: #ccc;
  display: flex;/*set display to flex*/
}
.sub-row-left-col {
  background: #ff0;
  display: inline-block;
  width: 25%;
  text-align: left;
}
.sub-row-right-col {
  background: #f0f;
  display: inline-block;
  width: 100%;/*set width to 100%*/
}
<body>

  <div class="sub-row-wrapper">

    <div class="sub-row-left-col">
      <p>Left img</p>
    </div>

    <div class="sub-row-right-col">
      <div class="post-content">
        <p>This should be positioned right of 'left img' and should not go underneath the left img</p>
      </div>
    </div>

  </div>

  <div class="sub-row-wrapper">

    <div class="sub-row-right-col">
      <div class="post-content">
        <p>This should be full width when I put enough content in to make it full width</p>
      </div>
    </div>

  </div>

</body>

<强>参考

flex

答案 1 :(得分:0)

.sub-row-left-col { 
    background: #ff0; 
    display:inline-block; 
    width: 25%;
   text-align: left; 
   float: left;
}

.sub-row-right-col { 
    background: #f0f; 
    display:inline-block; 
    width: 100%;  
}

应该做我相信的伎俩。 float: left;width:100%