将容器元素的宽度与子元素的宽度相匹配
我想要这样的设置:
<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/
btns 和块 div 根据内容获取宽度。就像小提琴中出现的那样,除了 btns 的宽度基于它们的文本而不是它们的容器
我不能使用表格,因为我需要能够应用样式来获得截然不同的外观,所以我需要 html 标记保持基本相同。如果绝对必要的话我可以应用一些js。
我尝试了几种不同的显示方式,但不确定如何实现这一点。我不希望硬编码任何宽度,因为内容会发生变化,并且我需要它在旧版本的 IE 中工作(尽管我可以使用 IE9.js 等库)。
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 libraries like IE9.js).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这里有一个示例,说明如何将 #block 的大小调整为与其最长按钮一样宽:
浮动元素将仅扩展到其内容的宽度。假设您希望每个按钮都在自己的行上。
如果您希望按钮一起流动,请从
.btn
规则中删除clear:both
。但是,如果您确实希望将它们全部放在一行上,则必须注意浮动下降。如果所有按钮加在一起的宽度大于可用宽度,就会发生这种情况。在这种情况下,最右边的按钮将下拉到其他按钮下方。更新:根据OP的评论,这里是表格单元格样式的CSS,其中
#block
和所有.btn
元素扩展到最宽的按钮宽度:以及示例。
Here's an example of how the #block will be sized to be as wide as its longest button:
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:Along with an example.
我不是 100% 确定我是否理解正确,但使用
display:inline
元素,如span
s 而不是s应该可以解决你的问题。
I'm not 100% sure whether I get you right, but using
display:inline
elements likespan
s instead of<div>
s should solve your problem.让它们浮动或内联,这样它们就不会像块一样(不会是 100% 宽度)。
make them float or inline, that way they won't act like blocks (wont be 100% width).