如何制作一个具有position:absolute的表格来扩展并填充其容器中的可用空间?

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

我的

table
里面有一个
div
table
具有
position: absolute
,其中
inset
定义为:

https://jsfiddle.net/dp4k9oc1/

<div>
  <table>
    <tr>
      <td>
        <label>hello</label>
      </td>
      <td>
        <label>hello</label>
      </td>
    </tr>
    <tr>
      <td>
        <label>hello</label>
      </td>
      <td>
        <label>hello</label>
      </td>
    </tr>
  </table>
</div>
table {
  position: absolute;
  inset: 50px;
  background-color: green;
  border-collapse: collapse;
}

div {
  width: 400px;
  height: 400px;
  background-color: yellow;
}

label {
  background: red;
}

table, th, td {
  border: 1px solid black;
}

看起来像这样:

enter image description here

如何使表格的宽度和高度填充 div,并且仍然尊重插图?例如。像这样的:

enter image description here

css
1个回答
0
投票

这可以通过将

height
width
添加到表中轻松实现,在您的情况下,我已将两者添加到
300px

为了将表格放在黄色框中居中,我将

position: relative
添加到
div
top
&
left
50vh
table

就这样,下面是工作示例。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
        body {
            margin: 0;
            padding: 0;
        }

        .mainDiv {
            color: white;
            width: 100%;
            height: 100vh;
            background-color: #1e1e1e;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        table {
            height: 300px;
            width: 300px;
            position: absolute;
            top: 50vh;
            left: 50vh;
            inset: 50px;
            background-color: green;
            border-collapse: collapse;
        }

        div {
            position: relative;
            width: 400px;
            height: 400px;
            background-color: yellow;
        }

        label {
            background: red;
        }

        table,
        th,
        td {
            border: 1px solid black;
        }
    </style>
</head>

<body>

    <div class="mainDiv">
        <div>
            <table>
                <tr>
                    <td>
                        <label>hello</label>
                    </td>
                    <td>
                        <label>hello</label>
                    </td>
                </tr>
                <tr>
                    <td>
                        <label>hello</label>
                    </td>
                    <td>
                        <label>hello</label>
                    </td>
                </tr>
            </table>
        </div>
    </div>

</body>

</html>

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