开发者

matching container element width with that of child

开发者 https://www.devze.com 2023-04-07 12:45 出处:网络
I want to have a setup like this: <div id=\"block\"> <div class=\"btn\">2</div> <div class=\"btn\">1235e</div>

I want to have a setup like this:

<div id="block">
<div class="btn">2</div>
<div class="btn">1235e</div>
<div class="btn">really long one</div>
</div>

jsfiddle: http://jsfiddle.net/cutcopypaste/3uu5Q/

Where the btns and block div get their width based on the content. Just like it appears in the fiddle, except that the width of the btns are based on their text rather than their container

I cannot use a table because I need to be able to apply styling to get vastly different appearance, so I need the html markup to stay basically the same. If it's absolutely necessary I could apply some js.

I tried a couple different ways of displaying, but not sure how to acheive this. I don't wish to hard-code any widths as the content will be changing, and I need it to work in older versions of IE (though I can use li开发者_如何转开发braries like IE9.js).


Here's an example of how the #block will be sized to be as wide as its longest button:

#block {
  float: left;
}  

.btn {
  float: left;
  clear: both; 
}

The floated elements will expand only to their content's width. It's assuming you want each button on its own line.

If you want the buttons to flow together, remove the clear:both from the .btn rule. However if you do want them all on one line you'll have to be aware of float drop. This will happen if the widths of all your buttons added together is greater than the available width. In this case, the rightmost button will drop down below the other buttons.

Update: based on OP's comment, here's the CSS for a table cell style where #block and all .btn elements expand to the widest button's width:

#block {
  display: inline-block;
}  

.btn {
  display: block;
}

Along with an example.


Where the btns and block div get their width based on the content.

I'm not 100% sure whether I get you right, but using display:inline elements like spans instead of <div>s should solve your problem.


make them float or inline, that way they won't act like blocks (wont be 100% width).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号