如何仅使用 CSS 让子级自动适应父级的宽度?
我有一个服务器端组件,它使用没有固定宽度的 DIV
生成流体布局“工具栏”,并在其中生成许多 A
。
然后我需要自定义该布局以使所有 A
标签自动适应父宽度。但是子级的数量是可变的,并且父级的宽度未知(它会自动适应窗口)。
我用这个小提琴做了一些测试: http://jsfiddle.net/ErickPetru/6nSEj/1/
但我找不到使其动态的方法(取消注释最后一个 A
标记以查看它如何不起作用,哈哈)。
我无法更改服务器端源来生成固定宽度的 HTML。如果有办法的话,我真的只想用 CSS 来解决这个问题,即使用 JavaScript 我也能达到这个结果。
如何使所有子项自动适应父项的宽度,而与子项的数量无关?
I have a server-side component that generates a fluid layout "toolbar" using DIV
without fixed width, generating many A
inside it.
Then I need customize that layout to make all A
tags auto fit to the parent width. But the number of children is variable and the parent's width isn't known (it auto fits itself to the window).
I made some tests with this Fiddle: http://jsfiddle.net/ErickPetru/6nSEj/1/
But I can't find a way to make it dynamic (uncomment the last A
tag to see how it ins't working, lol).
I can't change the server-side sources to gerenate HTML with fixed width. And I really would like to solve it only with CSS if there is any way, even that with JavaScript I could achieve that result.
How can I make all the children auto-fit itself to the parent's width independently of the number of children?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
display: table-cell
:参见: http://jsfiddle。 net/6nSEj/12/ (或有 5 个孩子)
这不会可以在 IE7 中工作,因为该浏览器根本不支持
display: table
等。You can use
display: table-cell
:See: http://jsfiddle.net/6nSEj/12/ (or with 5 children)
This won't work in IE7 because that browser simply doesn't support
display: table
and friends.这已经是一个很老的问题了。尽管当时给出的答案很受欢迎,但现在 Flexible Box Layout 提供了相同的结果,但更加简单,在所有现代浏览器中都有良好的支持。我强烈推荐它!
This is already a pretty old question. Although the answers given attended well at the time, nowadays the Flexible Box Layout offers the same result with much more simplicity, with good support in all modern browsers. I strongly recommend it!
目前许多人使用 jQuery 来解决这个问题。您所需要的只是一根线。这是你的小提琴。
For now many use jQuery as a solution to this problem. All you need is one line. This is from your fiddle.