设置子项的宽度以填充父项 [英] Set the width of children to fill the parent

查看:119
本文介绍了设置子项的宽度以填充父项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

小孩/家长问题:

我希望 div 的孩子填满它的宽度。



现在我正在使用这样的代码:

  .parent {width:100%;显示:内联块;身高:120px;背景:#000;填充:10px; box-sizing:border-box;}。child {display:inline-block;余量:1%;宽度:31.4%; height:100px;  

,它的工作方式是 3 boxes ,但是我想要的是 - 即使box的数量是 one 两个我希望他们填充父宽度。我只想使用 CSS

解决方案

使用 flexbox 属性实现此功能。



下面是一个演示:

.parent {display:flex;身高:120px;背景:#000;填充:10px; box-sizing:border-box;}。child {height:100px;背景:#ddd; flex:1; margin:0 10px;}

< div class =父> < div class =child>< / div> < div class =child>< / div> < div class =child>< / div>< / div>< div class =parent> < div class =child>< / div> < div class =child>< / div>< / div>< div class =parent> < div class =child>< / div>< / div>

Children/Parent issue :

I want the children of the div fill its width.

now am using a code like this:

.parent {
  width: 100%;
  display: inline-block;
  height: 120px;
  background: #000;
  padding: 10px;
  box-sizing: border-box;
}

.child {
  display: inline-block;
  margin-left: 1%;
  width: 31.4%;
  height: 100px;
  background: #ddd;
}

<div class="parent">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>

and it's working for 3 boxes, but what I want is that - Even if the box count is one or two i want them to fill the parent width. I want to achieve this using only CSS.

解决方案

You can achieve this using flexbox properties.

Here is a demo:

.parent {
  display: flex;
  height: 120px;
  background: #000;
  padding: 10px;
  box-sizing: border-box;
}

.child {
  height: 100px;
  background: #ddd;
  flex: 1;
  margin: 0 10px;
}

<div class="parent">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>

<div class="parent">
  <div class="child"></div>
  <div class="child"></div>
</div>

<div class="parent">
  <div class="child"></div>
</div>

这篇关于设置子项的宽度以填充父项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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