0

我有一个带有 2 个 div 的 html 页面,它们应该调整大小,但始终保持在一行中。我怎样才能建造这个?

我有以下示例 html 代码:

<html>
<head>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="content">
  <div id="table">
  <table>
    <tr>
      <td>ONE</td>
      <td>TWO</td>
    </tr>
  </table>
  </div>
  <div id="sidebar">
    <p>This is a sidebar</p>
  </div>
</div>
</body>
</html>

样式表如下所示:

#content {
  width: 100%;
}

#table {
  width: 100%;
  background-color: red;
  display: inline-block;
}

#sidebar {
  width: 170px;
  background-color: blue;
  float: right;
  display: inline-block;
}
4

5 回答 5

1

使用浮点数和 calc() 函数

这是使用浮点数和calc()函数(CSS3)的一种方法:

#content {
  width: 100%;
  border: 1px dotted gray;
  overflow: auto; /* useful for enclosing the floated region */
}
#table {
  float: left;
  width: calc(100% - 170px); /* modern but not yet widely supported */
  background-color: red;
}
#table table {
  border: 1px solid yellow;
  width: 100%; /* '100%' for full-width; 'auto' for shrink-to-fit content */
}
#sidebar {
  float: right;
  width: 170px;
  background-color: blue;
}

#table分别向左和#sidebar向右浮动。

当您浮动一个元素时,除非您指定宽度值,否则它的 with 将计算为缩小以适应值。

如果您指定width: 100%on #table,这将强制侧边栏从新行开始。

要为侧边栏留出空间,请使用calc(100% - 170px)计算表格面板的理想最大宽度。

calc()功能由最新的浏览器支持,因此该解决方案可能不适合。

见演示小提琴

于 2013-09-20T10:48:50.737 回答
1

将您的内容 css 更改为

#content {
width: 100%;
display:inline-block;
}

但是在这里,由于您的表格宽度设置为 100%,因此主 div 将如何在同一行中接受 170px。

#table 超过 81% 后,它会将内容推送到下一行

于 2013-09-20T10:02:29.373 回答
0

您将 #content 宽度设置为 100%,因此它将占用整个空间。您将需要调整 div 的宽度和将 #content 向左浮动,以便计算为 100%。

于 2013-09-20T10:02:04.940 回答
0
Float:left;

对于两个 div,然后将它们放在一个包装中,然后将包装调整为您希望它看起来的大小。

.wrap {

 width: 500px;
 height:800px;
}

因此,对于您的代码,CSS:

#content {
  width: 100%;
}
#wrap {
  height: 100%;
  width: 100%;
}
#table {
  width: 60%;
  background-color: red;
  display: inline-block;
  float: left;
}
#sidebar {
 width: 170px;
 background-color: blue;
 float: right;
 display: inline-block;
 float: left;
}

HTML:

<body>
<div id="wrap">
<div id="content">
  <div id="table">
  <table>
    <tr>
      <td>ONE</td>
      <td>TWO</td>
    </tr>
  </table>
  </div>
  <div id="sidebar">
    <p>This is a sidebar</p>
  </div>
</div>
</div>
</body>
于 2013-09-20T10:02:22.217 回答
0

看看这个小提琴......它有助于实现你所需要的。

这是更新的CSS ..

#content {
  width: 100%;
}

#table {
    float: left;
  background-color: red;
  display: inline-block;
    width: 60%;
}

#sidebar {
    float: left;
  width: 170px;
  background-color: blue;
  float: right;
  display: inline-block;
}
于 2013-09-20T10:04:53.813 回答