CSS选择器用于选择另一个元素之前的元素?

2022-01-10 00:00:00 css-selectors css

我正在为我的网站创建一个登录页面,我想在文本框获得焦点时将输入框之前的标签加粗.现在我有以下标记:

I'm working on a login page for my website and I want to bold the label that comes before the input box when the text box gains focus. Right now I have the following markup:

<label for="username">Username:</label>
<input type="textbox" id="username" />

<label for="password">Password:</label>
<input type="textbox" id="password" />

我可以使用相邻选择器选择标签after文本框,但我不能选择它之前的元素.我可以使用这个 CSS 选择器规则,但它只选择后面的标签,所以当用户名文本框获得焦点时,密码标签变为粗体.

I can use the adjacent selector to select the label after the text box, but I can't select the element before it. I can use this CSS selector rule, but it only selects the label after, so when the username text box gains focus, the password label becomes bold.

input:focus + label {font-weight: bold}

我能做些什么来完成这项工作吗?我知道 JavaScript 可以很容易地做到这一点,但如果可能的话,我想使用一个纯基于 CSS 的解决方案,我只是想不出办法.

Is there anything I can do to make this work? I know JavaScript could be used to easily do this, but I'd like to use a purely CSS-based solution if possible, I just can't figure out a way to do it.

推荐答案

如果 inputlabel 之前,则可以使用相邻兄弟选择器".只需将 input 放在 label 之前,然后修改布局将 label 放在 input 之前.这是一个例子:

It would be possible to use the 'adjacent sibling selector' if the input was before the label. Just put the input before the label, and then modify the layout to put label before the input. Here's an example:

<head runat="server">
    <title></title>
    <style type="text/css">
    input:focus + label {font-weight: bold}
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div style="direction:rtl">
        <input type="text" id="username" />
        <label for="username">Username:</label>
    </div>
    <div style="direction:rtl">
        <input type="password" id="password" />
        <label for="password">Password:</label>
    </div>
    </form>
</body>

(这是一种 hack,我个人会使用 javascript 来做到这一点)

(It's kind of a hack, I would personally use javascript to do this)

input:focus + label {font-weight: bold}

<form id="form1" runat="server">
  <div style="direction:rtl">
    <input type="text" id="username" />
    <label for="username">Username:</label>
  </div>
  <div style="direction:rtl">
    <input type="password" id="password" />
    <label for="password">Password:</label>
  </div>
</form>

相关文章