gpt4 book ai didi

html - 与它的
  • 父级大小相同,显示为 : table-cell
  • 转载 作者:太空宇宙 更新时间:2023-11-04 09:39:07 26 4
    gpt4 key购买 nike

    我有一个包含 a 的列表,有些只有一行,有些有两行。我如何使用 display:table-cell 强制使其具有与他的 li 父级相同的高度和宽度并垂直对齐文本?

    ul {
    display:table;
    width:700px;
    }

    li {
    display:table-cell;
    border-right:3px solid white;
    text-align:center;
    vertical-align:center;
    background-color:#ddd;
    }

    a {
    display:block;
    height:100%;
    background-color:#aaa;
    padding:1em 1.2em;
    }

    a:hover {
    background-color:red
    }
    <ul>
    <li><a href="">Example 1</a></li>
    <li><a href="">Example 2 two lines</a></li>
    <li><a href="">Example 3</a></li>
    <li><a href="">Example 4 two lines</a></li>
    <li><a href="">Example 5</a></li>
    <li><a href="">Example 6</a></li>
    <li><a href="">Example 7</a></li>
    </ul>

    最佳答案

    height:100% 仅当所有父项都设置了高度并且其中一个不是百分比时才有效(除非所有高度到 body 和 html 标签都有百分比高度)

    考虑到这一点,我们可以在 li 上设置 height:100%,然后为 ul 设置 0 的高度 - 如你已经使用了display:table,表格总是会增长到它们内容的高度

    ul {
    display:table;
    width:700px;
    height:0; /* add this */
    table-layout:fixed;
    }

    li {
    display:table-cell;
    vertical-align:middle;
    text-align:center;
    border-right:3px solid white;
    background-color:#ddd;
    height:100%; /* add this */
    }

    a {
    display:block;
    height: 100%;
    background-color:#aaa;
    padding:1em 1.2em;
    box-sizing: border-box; /* add this to get rid of the big gap at the bottom */
    }

    a:hover {
    background-color:red
    }
    <ul>
    <li><a href="">Example 1</a></li>
    <li><a href="">Example 2 two lines</a></li>
    <li><a href="">Example 3</a></li>
    <li><a href="">Example 4 two lines</a></li>
    <li><a href="">Example 5</a></li>
    <li><a href="">Example 6</a></li>
    <li><a href="">Example 7</a></li>
    </ul>

    更新

    好的,如果您只使用表格进行垂直对齐,那么我会将其更改为 flex - 它可以让您更好地控制子元素:

    ul {
    list-style: none;
    display: flex;
    width: 700px;
    }
    li {
    display: flex;
    margin-right: 3px;
    background-color: #ddd;
    box-sizing: border-box;
    flex-grow: 1;
    flex-basis: 0;
    }
    a {
    display: flex;
    align-items: center;
    text-align: center;
    flex-grow: 1;
    background-color: #aaa;
    padding: 1em 1.2em;
    box-sizing: border-box;
    }
    a:hover {
    background-color: red
    }
    <ul>
    <li><a href="">Example 1</a></li>
    <li><a href="">Example 2 two lines</a></li>
    <li><a href="">Example 3</a></li>
    <li><a href="">Example 4 two lines</a></li>
    <li><a href="">Example 5</a></li>
    <li><a href="">Example 6</a></li>
    <li><a href="">Example 7</a></li>
    </ul>

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com