CSS Div与孩子表现得像表,让一个孩子填充宽度[重复]

问题描述 投票:0回答:2

这个问题在这里已有答案:

所以我有一个<div>display:table;,它有10个孩子(计数可能会有所不同,孩子可能是按钮或输入)与display:table-cell;我已设置所有孩子的宽度,除了一个。我希望最后一个没有固定宽度的孩子填充宽度。

例如,假设父级<div>的宽度为600px,有4个按钮,每个按钮的宽度为40px,我希望第五个元素的宽度为440px而不设置静态。

这是我到目前为止所做的:

HTML:

<div class="table">
    <button class="show"></button>
    <div class="id">TEXT</div>
    <div class="username">TEXT</div>
    <div class="dob">TEXT</div>
    <button class="edit"></button>
    <button class="delete"></button>
</div>

而CSS:div

.table {
    display:table;
    width:100%;
    height:40px;
}
div.table > * {
    display:table-cell;
    height:40px;
    line-height:40px;
}
div.table > button {width:64px;}
div.table > div.id {width:48px;}
div.table > div.dob {width:128px;}

//编辑:我想要填充空间的元素是div.username

html css html-table css-tables
2个回答
2
投票

你可以用flexbox轻松完成

section {
  display: flex;
  max-width: 600px
}

div {
  flex: 0 40px;
  border: 1px solid red
}

div:last-of-type {
  flex: 1
}
<section>
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</section>

1
投票

简单地说,如果没有指定宽度,最后一个孩子将占用剩余空格:

.table {
  display: table;
  width:400px;
  border:1px solid green;
}

.table>div {
  display: table-cell;
  height:50px;
  border:1px solid red;
}

.item {
  width: 40px;
}
<div class="table">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div></div>
</div>

UPDATE

在你的情况下使用带有按钮元素的display:table-cell是不合适的,因为此属性不能应用于按钮(像其他一些按钮)。因此最好将按钮包含在spandiv中并在其上应用CSS。

以下是有用的链接,可以帮助您了解更多信息:

display: table-cell, border-spacing don't work with buttons?

Setting a <button>'s display as table-cell

© www.soinside.com 2019 - 2024. All rights reserved.