制作全宽而不设置`width`

时间:2016-08-24 11:57:39

标签: css

我将模拟我需要实现的目标。

例如,我希望 #2 占用整个空间,剩余100% - 180px ..如何实现?

enter image description here

P.S。设备支持flexboxcalc - http://css3clickchart.com/#flexbox

更受支持

4 个答案:

答案 0 :(得分:1)

使用css calc

这里有一个例子..这可能会有所帮助:

.class {
    width: -moz-calc(100% - 100px);
    width: -webkit-calc(100% - 100px);
    width: calc(100% - 100px);
}​

答案 1 :(得分:1)

您可以使用如下所示的flexbox模型。添加flex: auto;将允许正确的内容使用剩余宽度。

* {
  margin: 0;
  padding: 0;
}
html,
body {
  height: 100%;
}
#parent {
  display: flex;
  height: 100%;
}
#left {
  width: 180px;
  background-color: hotpink;
}
#right {
  flex: auto;
  background-color: dodgerblue;
}
<div id="parent">
  <div id="left"></div>
  <div id="right"></div>
</div>

答案 2 :(得分:0)

有很多方法可以做到这一点。一个简单的方法如下。

第一种方式:简单的内嵌块

.container {
  width: 100%;
  height: 600px;
  background-color: #f2f2f2;  
  }

.sidebar {
  background-color: red;
  width: 180px;
  height: 600px;
  float: left;
}
.main-content {
  display: inline-block; 
  background-color: green;  
}
<div class="container">
  <div class="main-content">Main Content</div>
  <div class="sidebar">Sidebar</div>
</div>

公平警告:在这种情况下,.main-content只会占用所需的空间,实际上并不是全宽。因此,如果要为其设置背景,则应将背景设置为.container。

第二种方式:使用calc进行宽度

.container {
  width: 100%;
  height: 600px;
  background-color: #f2f2f2;
  position: relative;
  }

.sidebar {
  background-color: red;
  width: 180px;
  height: 600px;
  float: left;
}
.main-content {
  float: right;
  background-color: green;  
  width: calc(100% - 180px);
  height: 600px;
}
<div class="container">
  <div class="main-content">Main Content</div>
  <div class="sidebar">Sidebar</div>
</div>

第三种方式:使用Flex

.container {
  width: 100%;
  height: 600px;
  background-color: #f2f2f2;
  display: flex;
  }

.sidebar {
  background-color: red;
  width: 180px;
  height: 600px;
}
.main-content {
  background-color: green;
  flex: auto;
}
<div class="container">
  <div class="sidebar">Sidebar</div>
  <div class="main-content">Main Content</div>
</div>

Flexbox可能是最好的解决方案,但据称旧浏览器不支持它。

这样做的第四种方式是使用伪造表的古老方式:

.container {
  width: 100%;
  height: 600px;
  background-color: #f2f2f2; 
  display: table;
  }

.sidebar {
  background-color: red;
  width: 180px;
  display: table-cell;
}
.main-content {
  display: table-cell;
  background-color: green;  
}
<div class="container">
  <div class="sidebar">Sidebar</div>  
  <div class="main-content">Main Content</div>
</div>

答案 3 :(得分:0)

您可以使用float: leftoverflow: hidden

aside {
  float: left;
  width: 30%;
  background: beige;
}
article {
  overflow: hidden;
  background: brown;
  color: white;
}
<aside>
  sidebar
</aside>
<article>
  content
</article>

相关问题