简体   繁体   English

将容器元素宽度与子元素宽度匹配

[英]matching container element width with that of child

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/ jsfiddle: http//jsfiddle.net/cutcopypaste/3uu5Q/

Where the btns and block div get their width based on the content. btns和block div根据内容得到它们的宽度。 Just like it appears in the fiddle, except that the width of the btns are based on their text rather than their container 就像它出现在小提琴中一样,除了btns的宽度是基于它们的文本而不是它们的容器

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. 我不能使用表格,因为我需要能够应用样式来获得截然不同的外观,所以我需要html标记保持基本相同。 If it's absolutely necessary I could apply some js. 如果绝对必要,我可以申请一些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 libraries like IE9.js). 我不希望硬编码任何宽度,因为内容将会改变,我需要它在旧版本的IE中工作(虽然我可以使用像IE9.js这样的库)。

Here's an example of how the #block will be sized to be as wide as its longest button: 以下是 #block的大小与最长按钮一样宽的示例

#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. 如果希望按钮一起流动,请从.btn规则中删除clear:both 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: 更新 :基于OP的注释,这里是表单元格样式的CSS,其中#block和所有.btn元素扩展到最宽按钮的宽度:

#block {
  display: inline-block;
}  

.btn {
  display: block;
}

Along with an example . 随着一个例子

Where the btns and block div get their width based on the content. btns和block div根据内容得到它们的宽度。

I'm not 100% sure whether I get you right, but using display:inline elements like span s instead of <div> s should solve your problem. 我不是百分之百确定我是否帮助你,但使用display:inline元素如span s而不是<div> s应该可以解决你的问题。

使它们浮动或内联,这样它们就不会像块一样(不会是100%宽度)。

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

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