如果div旁边没有其他元素,我怎么能让div填充100%宽度?

时间:2016-02-10 20:34:43

标签: html css

我有这样的简单标记(标签菜单):

var obj = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  },
};
fetch('https://example.com/login', obj)
  .then(function(res) {
    // Do stuff with result
  }); 

当所有元素具有相等的33%宽度以填充容器的100%时就是这种情况。

是否可以为所有自动检测的容器应用一般CSS规则,例如,是否只有一个其他容器或没有容器?然后调整标签的宽度? ( “STRECH到合适”)

也许是<div class="container"> <div class="tab1"></div> <div class="tab2"></div> <div class="tab3"></div> </div> min-width的某些内容?

3 个答案:

答案 0 :(得分:28)

根据what browsers you need to support,您可以使用flexbox:

&#13;
&#13;
$('.tab').click(function() {
  $(this).css('display', 'none');
});
&#13;
.container {
  display: flex;
}

.tab {
  border: 1px solid black;
  padding: 5px;
  flex: 1;
  margin: 5px;
}
&#13;
<p>Click a tab to remove it</p>
<div class="container">
   <div class="tab">Tab 1</div>
   <div class="tab">Tab 2</div>
   <div class="tab">Tab 3</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:15)

你的意思是像flexbox?

&#13;
&#13;
.container {
  display: flex;
  height: 50px;
  margin-bottom: 1em;
}
[class*="tab"] {
  flex: 1;
  border: 1px solid red;
}
&#13;
<div class="container">
  <div class="tab1"></div>
</div>

<div class="container">
  <div class="tab1"></div>
  <div class="tab2"></div>
</div>

<div class="container">
  <div class="tab1"></div>
  <div class="tab2"></div>
  <div class="tab3"></div>
</div>
&#13;
&#13;
&#13;

或CSS表

&#13;
&#13;
.container {
  display: table;
  height: 50px;
  width: 100%;
}
[class*="tab"] {
  display: table-cell;
  border: 1px solid red;
}
&#13;
<div class="container">
  <div class="tab1"></div>
</div>

<div class="container">
  <div class="tab1"></div>
  <div class="tab2"></div>
</div>

<div class="container">
  <div class="tab1"></div>
  <div class="tab2"></div>
  <div class="tab3"></div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:6)

您可以使用display:tabledisplay:table-cell查看以下代码

HTML:

<div class="container">
   <div class="tab">Tab 1</div>
   <div class="tab">Tab 2</div>
   <div class="tab">Tab 3</div>
</div>

CSS:

.container {
  display: table;
  width:100%;
}

.tab {
  border: 1px solid black;
  padding: 5px;
  display: table-cell;
  margin: 5px;
}