html 为什么星号只出现在某些字段中?

ddrv8njm  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(109)

在HTML和(S)CSS中,我做了一个表单作为我家庭作业的一部分。(见https://codepen.io/quokka-wiki/pen/BavqrQL
我添加了以下HTML/SCSS,以便在必填字段的标签上添加一个红色星号:

<html>
    <!-- ... -->
    <body>
        <!-- ... -->
        <label for="username">Username</label>
        <input type="text" name="username" required />

        <label for="password">Password</label>
        <input type="password" name="password" required />

        <!-- ... -->
        <input type="checkbox" name="tos" required />
        <label for="tos">I agree to sell my soul to the Devil for this app</label>
        
    </body>
</html>

但出于某种原因,它只对其中一些人有效。
有人能帮我弄清楚/帮我找到一个更好的CSS选择器吗?

更新:

我不知道为什么在上面的代码片段中它根本不起作用,只要转到the codepen

h7wcgrx3

h7wcgrx31#

根据上面的评论,您的选择器不正确。由于你代码中的label元素在input元素之前(并且所需的属性被分配给那个input元素),在css规则中使用加号+将无法找到你实际想要的标签-相反,如果碰巧有一个标签(将用于不同的元素),选择器将匹配并应用样式。
第一个代码片段基本上是按照你的代码使用相同/相似的选择器,你会看到下面的标签是黄色的,而不是一个应该是。

:required + label{background:yellow}
:required + label:after{content:'*';color:red}
<label for="username">Username</label>
<input type="text" name="username" required />

<label for="password">Password</label>
<input type="password" name="password" required />

相反,如果你改变label & input元素的顺序,你会得到input元素下面的文本,这可能不是必需的布局,但你会看到选择器现在如何正确地将样式应用到正确的元素。

:required + label{background:yellow}
:required + label:after{content:'*';color:red}
<input type="text" name="username" required />
<label for="username">Username</label>

<input type="password" name="password" required />
<label for="password">Password</label>

作为一个软糖,你可以玩定位伪内容以上的输入使用负边距-这不是优雅的,但排序的作品。

:required + label:after{
  content:"*";
  color:red;
  position:relative;
  top:-2.5rem;
  margin:0 0 0 0.5rem;
}

label:before{
  content:attr(for);
  position:relative;
  top:-2.5rem;
  z-index:2;
  text-transform:capitalize;
}

label{display:block}

input{margin:2rem 0 0 0}
<input type="text" name="username" required />
<label for="username"></label>

<input type="password" name="password" required />
<label for="password"></label>
vwoqyblh

vwoqyblh2#

您使用的选择器:required + label::after读作“A required field,immediately followed by a label.”换句话说,您的CSS代码要求label位于输入元素之后。这就是它在密码字段上工作的原因,因为该标签位于用户名的必填字段之后。
如果您想保持元素的顺序,简单的解决方法是使用一个类,并将其应用于所需输入的标签。
您也可以使用:has selector来完成此操作,规则如下:label:has(+ :required)::after。Firefox目前不支持这个选择器,所以使用类是更好的选择。

相关问题