简体   繁体   English

如何设置带有内部浮点的div样式以水平扩展以允许所有内部浮点的div都适合?

[英]How do I style a div with inner floats to expand horizontally to allow all inner floating divs to fit?

Basically, I have a content box with some floating items: 基本上,我有一个带有一些浮动项目的内容框:

html

<div class="contentBox">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item">4</div>
</div>

css

.contentBox {
    overflow-x:scroll;
}
.item {
    float:left;
}

I want the box to expand in width to let as many items as I add to it to fit, floating left (which means the elements get pushed to the right). 我希望框的宽度扩大,以允许我添加到其中的项目尽可能多地向左浮动(这意味着元素被推到右侧)。 But instead it only goes as wide as the page before the items drop down because of having no room. 但是相反,由于没有空间,它只能放大到下拉项目之前的页面宽度。 I want it to continue on outside of the page. 我希望它在页面外继续。

How do I do this? 我该怎么做呢?

I'm thinking I'll need to use some JavaScript, but I'd rather a pure CSS solution if it's possible. 我认为我需要使用一些JavaScript,但如果可能的话,我宁愿使用纯CSS解决方案。

You can use white-space: nowrap on parent container with inline-block child elements: 您可以在带有内联块子元素的父容器上使用white-space: nowrap

.contentBox {
    overflow-x: scroll;
    white-space: nowrap;
}
.item {
    display: inline-block;
}

Demo: http://jsfiddle.net/vo8202uy/ 演示: http//jsfiddle.net/vo8202uy/

 $('button').click(function() { $('.contentBox').append('<div class="item">' + ($('.item').length+1) + '</div>'); }); 
 .contentBox { overflow-x:scroll; white-space: nowrap; } .item { width: 50px; background: coral; margin-right: 5px; display: inline-block; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="contentBox"> <div class="item">1</div> <div class="item">2</div> <div class="item">3</div> <div class="item">4</div> </div> <button>Add more</button> 

You can set display: table-cell for .item . 您可以将display: table-cell.item

Here's an example: http://jsfiddle.net/andunai/fq201q8b/ 这是一个示例: http : //jsfiddle.net/andunai/fq201q8b/

Here you GO :) Only add this on you button click. 在这里,您可以:)仅在单击按钮时添加它。

$('button').click(function() {
  var item = $('.item').length + 1;
   $('.contentBox').append('<div class="item">' + item + '</div>');

   var w = window.innerWidth;
   var l = $(".contentBox div").length + 1;
   $(".contentBox div").each(function(){
        $(this).css("width", w/l);
   });
});

Check this JSFiddle Link http://jsfiddle.net/DynamicRemo/8krcm0x6/ 检查此JSFiddle链接http://jsfiddle.net/DynamicRemo/8krcm0x6/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM