首页 > 解决方案 > CSS 如果第一个元素是下拉菜单,那么做一些事情

问题描述

我有 CSS 问题,我正在寻求帮助 :)

所以这里是我的页面: 在此处输入图像描述

页面左下角有通知图标,有时可以禁用,图标和切换按钮会消失。如果消失,我的“语言”下拉菜单会像这样向左移动: 在此处输入图像描述

我的问题是我不知道在 CSS 中如何说“Langage”下拉菜单是否是我的行的第一个元素,然后做一些事情(例如添加填充)。

CSS中有办法做到这一点吗?

我试过这样的事情:

   &:first-child {
    margin-left: ${spacings.medium_2};
   }

但不工作:/

我的代码(反应代码):

    {projectNotification
    && (
      <UserFormLine id="notifications_switch" xs={6}>
        <Icon>notifications</Icon>
        <SwitchNotifications
          id="notification"
          checked={user.notify}
          onChange={() => handleChangeUserAttribute('notify', !user.notify)}
        />
      </UserFormLine>
    )
    }
     <ProjectFormLine id="languageId_formLine" xs={6}>
          <DropDown
            id="languageId"
            source={appLocalesData}
            label={formatMessage({ ...messages.user.language })}
            value={user.language}
            onChange={(value) => handleChangeUserAttribute('language', value)}
          />
        </ProjectFormLine>

标签: css

解决方案


first-child应该可以正常工作,如果您想对规则的特异性进行更多控制,可以尝试使用另一个属性来确保样式适用于与该属性匹配的元素。

在此示例中,该规则将应用于作为 的第一个子元素的元素container,但也具有name带值的属性testinput1

.container {
  margin-bottom: 10px;
}

.container input[name="testinput1"]:first-child {
  border: 1px solid red;
}
<div class="container">
  Container 1
  <input class="input" name="testinput1" />

  <input class="input" name="testinput2" />

</div>

<div class="container">
  Container 2
  <input class="input" name="testinput2" />

  <input class="input" name="testinput1" />

</div>

<div class="container">
  Container 3
  <input class="input" name="testinput1" />

  <input class="input" name="testinput2" />

</div>

但是,看看你的场景,也许你想研究CSS Grid来构建你的布局,你可以设置它,所以通知控件应该有一个“空”列,所以它保持其他元素对齐。

或者visibility: hidden也按照评论中的建议使用通知控件上的属性。


推荐阅读