CSS属性选择器和输入标记的伪元素之间的区别

brgchamk  于 2023-06-07  发布在  其他
关注(0)|答案(2)|浏览(109)

<input type="text" placeholder="nothing" title="google" required>

内部CSS文件:

input[type="text"]{
border: 2px solid red;
}

input::placeholder{

color:green;
}

input[title="google"]{
background-color:black;
color:white;
}

为什么typeplaceholdertitle的编写过程不同?虽然标签内的文字看起来是一样的。如何理解哪些是属性,哪些是元素

uklbhaso

uklbhaso1#

input::placeholder选择<input>的占位符,而input[attribute="value"]选择<input>,其属性值为value。它们有不同的功能。
可视化示例:

/* Selects an <input> with a 'placeholder' attribute */
input[placeholder] {
  color: #2ab7ca;
}

/* Selects the placeholder itself */
input::placeholder {
  color: #ff6b6b;
}

/* Ignore these */

body {
  margin: 0;
  padding: 2em;
}

input {
  display: block;
  margin: 1em 0;
  height: 2em;
  width: 100%;
  padding: 0.5em;
}
<input
  type="text"
  placeholder="This placeholder is red and not editable."
>

<input
  type="text" placeholder=""
  value="...whereas the input content itself is blue and editable."
>

注意:这个答案是从一个评论转换而来的,因为我找不到任何重复的目标。

r8xiu3jd

r8xiu3jd2#

在CSS中,我们有属性选择器和伪元素,它们有不同的用途和不同的语法。让我们了解它们的区别以及如何识别它们:

Attribute Selectors:
    Attribute selectors allow us to target elements based on their attribute values.
    To use them, we enclose the attribute and its value in square brackets, like this: [attribute="value"].
    For example, in your code, input[type="text"] targets <input> elements that have their type attribute set to "text".
    Similarly, input[title="google"] targets <input> elements with the title attribute set to "google".
    With attribute selectors, we can apply styles to elements based on specific attribute values.

Pseudo-Elements:
    Pseudo-elements, on the other hand, allow us to target specific parts or states of an element.
    We indicate a pseudo-element by using double colons :: before the element name.
    For instance, input::placeholder targets the placeholder text of <input> elements.
    Pseudo-elements enable us to style pseudo-parts or states, such as the placeholder text, first letter, or first line of an element.

要区分属性选择器和伪元素,请执行以下操作:

Attribute selectors use square brackets [attribute="value"] to target elements based on their attribute values.
Pseudo-elements use double colons :: before the element name to target specific parts or states of elements.

在CSS代码中,选择器input[type=“text”]、input[title=“google”]和input::placeholder分别针对元素的不同方面:

input[type="text"] applies styles to <input> elements that have the type attribute set to "text".
input[title="google"] targets <input> elements with the title attribute set to "google".
input::placeholder targets the placeholder text within <input> elements.

通过使用这些选择器,我们可以根据元素的属性或状态将独特的样式应用于特定的元素或元素的部分。

相关问题