如何让孩子自动适应父的宽度只有CSS? [英] How to make children auto fit parent's width only with CSS?

查看:127
本文介绍了如何让孩子自动适应父的宽度只有CSS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务器端组件,使用 DIV 生成流体布局工具栏,没有固定宽度,生成许多 A 里面。

I have a server-side component that generates a fluid layout "toolbar" using DIV without fixed width, generating many A inside it.

然后我需要自定义布局,使所有 A 标签自动适合父宽度。但是,孩子的数量是变量,父的宽度不知道(它自动适应窗口)。

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).

我用这个小提琴做了一些测试: http://jsfiddle.net/ErickPetru/6nSEj/1/

I made some tests with this Fiddle: http://jsfiddle.net/ErickPetru/6nSEj/1/

但我找不到一个方法使它动态(取消注释最后的 A 标签,看看它不工作,lol)。

But I can't find a way to make it dynamic (uncomment the last A tag to see how it ins't working, lol).

我无法更改服务器端来源以固定宽度的HTML。我真的想解决它只有CSS如果有任何方式,即使使用JavaScript我可以实现这个结果。

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?

推荐答案

这已经是一个很老的问题。尽管当时的答案很好,但现在灵活框布局同样的结果更加简单,在所有现代浏览器中都具有良好支持。我强烈推荐它!

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!

/* Important parts */
.parent {
  display: flex;
}

.parent a {
  flex: 1;
}

/* Decoration */
.parent {
  padding: 8px;
  border: 1px solid #ccc;
  background: #ededed;
}

.parent a {
  line-height: 26px;
  text-align: center;
  text-decoration: none;
  border: 1px solid #ccc;
  background: #dbdbdb;
  color: #111;
}

<div class="parent">
  <a href="#">Some</a>
  <a href="#">Other</a>
  <a href="#">Any</a>
</div>

<br>

<div class="parent">
  <a href="#">Some</a>
  <a href="#">Other</a>
  <a href="#">Any</a>
  <a href="#">One More</a>
  <a href="#">Last</a>
</div>

这篇关于如何让孩子自动适应父的宽度只有CSS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆