【问题标题】:Stretch content to 100% of container width, minus the width of a floated sibling element将内容拉伸到容器宽度的 100%,减去浮动同级元素的宽度
【发布时间】:2015-12-07 21:54:21
【问题描述】:

我想在容器内的某些内容旁边放置一个动态徽标(宽度可变/未知)(请参阅随附的模型 - 徽标位于右侧,绿色,内容为蓝色)。我特别希望内容 div 拉伸到页面的全部剩余宽度,如模型所示:

但是当我尝试将内容浮动到左侧并将徽标浮动到右侧 (jsfiddle) 时,除非我将内容宽度设置为小于 100%(而且我不能知道内容宽度,因为徽标宽度可能会有所不同)。

HTML:

<div id="container">
  <div id="content"></div>
  <div id="logo"></div>
</div>

CSS:

#content {
  border: 1px solid green;
  height: 300px;
  width: 100%;
  float: left;
}

#logo {
  border: 1px solid red;
  width: 50px; /*unknown width*/
  height: 50px;
  float: right;
}

如何将内容 div 拉伸到整个容器宽度,减去徽标的宽度?

【问题讨论】:

  • 既然两者都有不固定的宽度,那么你应该使用 JavaScript 解决方案,你需要一个 JS 解决方案(这样你就可以使用窗口上可用的全宽度)?
  • 可以用 SASS/SCSS 来完成...您可以从 DIV 中减去徽标的宽度。在那里你可以进行计算。但是这里你使用的是 CSS,所以最好的方式是使用 JS。

标签: css


【解决方案1】:

这是一种使用 jQuery 的可能方法:

jsFiddle demo

jQuery:

$(document).ready(function() {

    var logoWidth = $('#logo').width();
    var docWidth = $(document).width();
    $('#content').width(docWidth-logoWidth);

});

CSS:

html, body {
    margin:0;
    padding:0;
}
#content {
  background-color: lightblue;
  height: 200px;
  width: 100%;
  float: left;
}
#logo {
  background-color: green;
  width: 50px; /*unknown width*/
  height: 50px;
  float: right;
}

HTML:

<div id="container">
    <div id="content"></div>
    <div id="logo"></div>
</div>

Source


编辑:根据您提供的 CSS,我将 margin:0; 和 padding:0 添加到 html,body 以确保 document 宽度代表两个 DIV 的实际可用空间。 如果body或html或您使用的容器确实有margin、padding或border,您可以使用此代码代替上一个代码:

jsFiddle demo

jQuery:

$(document).ready(function () {

    var logoWidth = $('#logo').width(),
      docWidth = $(document).width(),
      marginB = $('body').outerWidth(true) - $('body').outerWidth(),
      paddingB = $('body').innerWidth() - $('body').width(),
      borderB = $('body').outerWidth() - $('body').innerWidth();

    $('#content').width(docWidth - logoWidth - marginB - paddingB - borderB);

});

Source

【讨论】:

    【解决方案2】:

    根据您的浏览器支持要求,flexbox 可以做到这一点

    .container {
      display: flex;
      margin-bottom: 1em;
    }
    .content {
      background: green;
      height: 100px;
      flex: 1;
    }
    .logo {
      background: red;
      width: 50px;
      height: 50px;
    }
    .large {
      width: 100px;
    }
    <div class="container">
      <div class="content"></div>
      <div class="logo "></div>
    </div>
    
    <div class="container">
      <div class="content"></div>
      <div class="logo large"></div>
    </div>

    【讨论】:

    • 我认为你不需要担心浏览器的支持,除非你还在为古老的浏览器开发。在这里查看caniuse.com/#feat=flexbox
    • 在处理 Stack Overflow 上的 unknown 要求时,支持总是值得提及。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 2011-07-31
    • 1970-01-01
    • 2012-12-22
    相关资源
    最近更新 更多