CSS 如何填充整个宽度

CSS how to fill the entire width?

本文关键字:填充 何填充 CSS      更新时间:2023-09-26

我已经戴上了护目镜,但仍然不知道该怎么办

我有 3 个分区

<body>
    <div id="container">
        <div id="center"> <h1>center</h1> </div>
        <div id="right"> <h1>right</h1> </div>
    </div>
</body>

我试图完成什么

  • div id=中心是自动填充宽度
  • div id=right 位于div id=center, width=200px 的右侧位置;

到目前为止我尝试了什么

#center{
    background-color: green;
        float: left;
        overflow: auto;
}
#right{
    background-color: red;
        float: right;
        width: 200px;
}

如何使div id=center 在它的右位置用另一个div (div id=right) 填充整个宽度

斯菲德尔

原谅我的英语

如果你需要一个纯粹的CSS解决方案,那么考虑改变你的DOM

演示

首先,从#center中删除float: left;属性,然后我添加了width: auto;overflow: hidden;属性,这将使列独立。

参考代码 :

<div id="container">
    <div id="right"></div>
    <div id="center"></div>
</div>
#container {
    height: auto;
    overflow: hidden;
}
#center {
    background-color: green;
    width: auto;
    height: 20px;
    overflow: hidden;
}
#right {
    background-color: red;
    float: right;
    height: 20px;
    width: 200px;
}

不是这样工作的 - 你需要将"右"div嵌套在"中心"div 中:

<body>
  <div id="container">
    <div id="center">
      <h1>center</h1> 
      <div id="right">
        <h1>right</h1> 
      </div>
    </div>
  </div>
</body>

然后使h1内联显示:

h1 {
  display: inline-block;
}
#center {
  background-color: green;
  float: left;
  width: 100%;
}
#right {
  background-color: red;
  float: right;
  width: 200px;
}

这是一个更新的小提琴。

我从这里得到了这个,并学到了一个新的/有用的。

以下解决方案不会影响您的 dom 进行更改。

#center{
    background-color: green;
    float: left;
    width: -moz-calc(100% - 200px);
    width: -webkit-calc(100% - 200px);
    width: calc(100% - 200px);
}

演示

添加这个单独的,因为另一个可能对将来的某人有用。这是我能想到的唯一 CSS 解决方案,但有一个警告:您必须在两个div 上使用基于百分比的宽度:

#center {
  background-color: green;
  display: inline-block;
  float: left;
  width: 80%;
}
#right {
  background-color: red;
  float: left;
  width: 20%;
}

20% 应该接近您在较小div 上所需的内容,如有必要,您可以使用媒体查询来防止它在较大屏幕上太宽。

这是一个更新的小提琴。

我能做的是自定义你的css:

#center{
    background-color: green;
    position : absolute;
    width : 100%;
    z-index : -1;
}

#center填充它和#right之间的所有空白空间。
但你必须注意到,#center#right