1

这是我的 HTML 片段,

<div class=bigger>
    <div>A</div>
    <div>B</div>
    <div>C</div>
</div>

如果我有这样的 CSS:

.bigger
{
  height: 300px;
}

CSS中有什么方法可以使所有子div的高度与父div相同,即所有子div都应该有300px的高度?

4

6 回答 6

3

如果你想在纯 CSS 中实现这一点,你可以试试这个

演示

我已经为 4 个项目设置了它。您可以将其扩展到您想要的任意数量的项目。

/* one item */
.bigger > div:first-child:nth-last-child(1) {
    height: 300px;
}

/* two items */
.bigger > div:first-child:nth-last-child(2),
.bigger > div:first-child:nth-last-child(2) ~ div {
    height: 150px;
}

/* three items */
.bigger > div:first-child:nth-last-child(3),
.bigger > div:first-child:nth-last-child(3) ~ div {
    height: 100px;
}

/* four items */
.bigger > div:first-child:nth-last-child(4),
.bigger > div:first-child:nth-last-child(4) ~ div {
    height: 75px;
}
于 2013-10-28T11:18:08.790 回答
3

使用 Flexbox 的解决方案:

.bigger {
  height: 400px;
  background: #eea;

  display: flex;
  flex-direction: column;
}

.bigger div {
  margin: 4px;
  border: 1px dotted green;
  flex: auto;   
}

Demo: http://codepen.io/anon/pen/nAjLt (Note that Codepen does vendor prefixing)

于 2013-10-28T11:19:34.647 回答
1
.bigger {
    width:100%;
    height:auto;
    border:1px solid red;
}
.bigger div {
    height:100px;
    width:100%;
    border:1px solid blue;
}

为您的目的使用此 css,通过设置heightauto it will adjust to any no of divs.

.bigger div还将所有 div 设置为 100px 高度。

现场演示

编辑:对于固定容器

.bigger {
    width:100%;
    height:300px;
    border:1px solid red;
    display:table;
}
.bigger div {
    display:table-row;
    height:auto;
    width:100%;
}

现场演示2

所有浏览器也一样:)

于 2013-10-28T11:15:26.950 回答
1

允许元素占据等量的空间是传统上只有使用<table>s 才能实现的。但是,您可以使用 CSS 使您<div>的 s 表现得像<table>s

HTML

<div class=bigger>
    <div>A</div>
    <div>B</div>
    <div>C</div>
    <div>A</div>
    <div>B</div>
    <div>C</div>
    <!-- add or remove any number of <div>s here -->
</div>

(相关)CSS

.bigger {
    display: table;
    height: 300px;
    width: 100%;
}

.bigger > div {
    display: table-row;
    border-top: 1px solid black;
    border-bottom: 1px solid black;
}
于 2013-10-28T11:17:07.117 回答
1

要与孩子和父母一起工作,您需要使用automax

<div class="bigger">
 <div>A</div>
 <div>B</div>
 <div>C</div>
</div>

在这里你可以使用

.bigger {
  height: auto; // this will do the trick..
  overflow: none;
  min-height: 300px;
}

使用最大值和最小值,只是为了确保height每次孩子增加或减少时保持不变,然后使用这个:

.bigger div {
  height: 100%; // note this..
}

在这里试试这个小提琴:http: //jsfiddle.net/afzaal_ahmad_zeeshan/2bJfW/添加一个 div 更多并检查它,

如果你想动态创建 div 高度,那么就没有 CSS,你需要 JS 或者说 jQuery。因为您需要计算孩子的数量,然后更改他们的身高百分比,让我们说从10030(3)或22(4)等等,因为文本不适合那个大小。

于 2013-10-28T11:17:37.333 回答
1
.bigger
{
  height: auto;
}
.bigger div
{ 
height:50px;
}

You should mentioned height of each inner div,then only it works properly.

Now u add another inner div elements inside of bigger div the height should be same.

Here I have mentioned height 50px, u give at what height you wants.

于 2013-10-28T11:32:28.630 回答