简体   繁体   中英

Define parent div tag width, according to children tags (Using css)

I have parent div tag and him must be several children div tags, I want that children tags placing horizontal. count childrens div tags, is not known advanced, on this, I can't set width parent div tag with css, for this I use js

var cnt = $("#parent div").length; // obtain children tags total count
var parent_width = cnt * 102 ;  // 100 is children tag width and 2 is left and right border sum : 100 + 1 + 1

$("#parent").css({
    width: parent_width+"px"
});




<div id="parent" style="height: 100px; background-color: #090">
    <div style="height: 100px; width: 100px; background-color: #009; border: 1px solid #ccc; float: left">
    </div>
    <div style="height: 100px; width: 100px; background-color: #009; border: 1px solid #ccc; float: left">
    </div>
</div>

This works, but I think this must make without js, only with css, please tell how ?

Solution:

HTML

<div id="parent">
    <div></div>
    <div></div>
    <div></div>
</div>​

CSS

​#parent {
    float: left;
    height: 100px; 
    background-color: #090;  
}

#parent​ > div {
    height: 100px; 
    width: 100px; 
    background-color: #009; 
    border: 1px solid #ccc; 
    float: left;
}​

Result: http://jsfiddle.net/khEKS/

You can use the following CSS for the parent element:

#parent
{
  background-color:#090;
  height:100px;
  float:left;
}

That way the parent div will get the appropriate width automatically so that the children can fit into it.

And of course, you have to specify float property on the child div elements as well if you want them to be in the same line.

display: inline-block;

Will do work for you.

You can use the following CSS for the parent element:

 #parent { height: 100px; background-color: #090 display: inline-block; } #parent > div { height: 100px; width: 100px; background-color: #009; border: 1px solid #ccc; } 
 <div id="parent"> <div></div> <div></div> <div></div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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