dynamically add a set of DIVs inside another DIV
CSS is not really my thing and when I see position relative, static or absolute my head starts to spin :(
So the question is: I have a DIV and inside it I need to put an arbitrary number of <div>
s aligned horizontally. This will be done in runtime since I dont know the amount of DIVs nor the width for each one at design time.
For example lets say I have the following array of DIVs to add:
_aDIVs = [[40, '#red'], [10, '#green'], [40, '#blue'], [10, '#brown']];
- First DIV needs to fill from 0% to 40% of parent DIV and the BG color is red
- Second from 41% to 50% with BG color green
- Third from 51% to 90%, blue
- Fourth from 91% to 100%, brown
Each DIV will have a different background color, the % are know only at runtime. It's important to use % because otherwise the filling will break when the browser window re-sizes. The idea is something like this:
|--------------------- PARENT DIV ---------------------|
|------RED------||-GREEN-||-----BLUE-----||-BROWN-|
(sorry for my drawing skills!)
Right now, the parent DIV is using position absolute, here's the exact declaration:
div id="slider开发者_如何转开发-addon" style="height: 5px; position: absolute; bottom: 0px; width: 100%; background-color: red; ">
I don't care if there is an obscure trick where the first DIV fill 100% but then it get overlapped by the next <div>
and so on, as long the trick is cross-browser compatible (need to work on IE, FF & Chrome)
Also, if there is a way to have multiple background colors horizontally aligned on the parent DIV that will accomplish the same effect as long as the fill % can be specified.
Thanks!
UPDATE:
Solved with ShankarSangoli method, here's the solution with a minor correction:
var _aDIVs = [[40, '#3399FF'], [10, '#33CC33'], [40, '#FFCC00'], [10, '#CC66FF']];
var $sliderDiv = $("#slider-addon");
$.each(_aDIVs, function(i, val) {
$sliderDiv.append(
$('<div></div>').css({ 'float': 'left', 'width': val[0] + '%',
'background-color': val[1], 'height': '5' })
);
});
Thank you :)
You cannot have multiple background colors to any element. To accomplish your goal you can try something like this. To set the background color and other styles you can use css as below
#red{
background-color: red;
}
#blue{
background-color: blue;
}
var $sliderDiv = $("#slider-addon");
var sliderWidth = $sliderDiv.width();
$.each(_aDivs, function(i, val){
$sliderDiv.append($(val[1]).css({float:"left":width:parseInt((sliderWidth*val[0])/100)+"%"}));
});
I think this is what you're after:
http://jsfiddle.net/d4Yft/
<div id="foo" style="width: 100px;">
<div style="background-color: blue; width: 25px; height: 15px; display: inline-block;"></div>
<div style="background-color: red; height: 15px; width: 15px; display: inline-block;"></div>
<div style="background-color: green; height: 15px; width: 20px; display: inline-block;"></div>
</div>
Use "display:inline-block;" for the child divs.
EDIT:
http://jsfiddle.net/XDwNa/
精彩评论