【问题标题】:How can I make it so the first element in a DIV has a different CSS to others?如何使 DIV 中的第一个元素具有与其他元素不同的 CSS?
【发布时间】:2014-02-27 18:09:24
【问题描述】:

我有以下 LESS 代码:

.modal-input-row {
        padding-bottom: 1rem;
        padding-top: 1rem;
        overflow: hidden;
        display: block;

        div {
            float: left;
            width: 50%;

            input {
                box-sizing: border-box;
                margin-bottom: 0.1rem;
                width: 75%;
            }

        }
    }

如何使外部容器内的第一个 modal-input-row 在顶部没有填充?

【问题讨论】:

  • 为它提供小提琴。
  • 这取决于您的标记,也可以发布 HTML。

标签: html css less


【解决方案1】:

使用:first-child伪类

.outercontainer .modal-input-row {
    padding-bottom: 1rem;
    padding-top: 1rem;
    overflow: hidden;
    display: block;

    &:first-child {
       padding-top: 0;
    }

    ...

}

【讨论】:

  • :first-child 表示子树中的第一个元素。它可能会或可能不会选择第一个.modal-input-row
【解决方案2】:

使用:first-child 伪选择器:

input {
    box-sizing: border-box;
    margin-bottom: 0.1rem;
    width: 75%;
    &:first-child {
        padding-top: 0;
    }
}

但是,如果您希望第一个 .modal-input-row 中的 input 没有顶部填充:

.modal-input-row {
    padding-bottom: 1rem;
    padding-top: 1rem;
    overflow: hidden;
    display: block;

    div {
        float: left;
        width: 50%;

        input {
            box-sizing: border-box;
            margin-bottom: 0.1rem;
            width: 75%;
        }

    }
    &:first-child input {
        padding-top: 0;
    }
}

【讨论】:

  • 这取决于标记。如果每个 div 元素中只有一个输入,那么它们都会被选择器处理。
  • 另外,.modal-input-row:first-child 可能不起作用,因为 :first-child 代表其父级中的第一个 元素,而不是第一个 。正如我所说,这取决于标记。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-20
  • 1970-01-01
  • 2011-03-06
  • 2013-05-12
  • 1970-01-01
  • 1970-01-01
  • 2021-11-06
相关资源
最近更新 更多