Skip to content

Селекторы по атрибутам

[attr]

  • [attr] - селектор наличия атрибута attr.

Например. Изменим файл index.html:

index.html
html
<body>
    <input type="text" placeholder="Имя" />
    <input type="text" />
    <input type="text" placeholder="Возраст" />
</body>

Изменим файл styles.css:

styles.css
css
input[placeholder] {
    border: 2px solid green;
}

[attr="value"]

  • [attr="value"] - селектор по точному значению.

Например. Изменим файл index.html:

index.html
html
<body>
    <span data-type="error">Ошибка</span>
    <span data-type="success">Успешно</span>
    <span data-type="error">Ещё одна ошибка</span>
</body>

Изменим файл styles.css:

styles.css
css
span[data-type='error'] {
    color: red;
    font-weight: bold;
}

[attr^="val"]

  • [attr^="val"] - значение начинается с val.

Например. Изменим файл index.html:

index.html
html
<body>
    <div class="card-primary">Карточка 1</div>
    <div class="card-secondary">Карточка 2</div>
</body>

Изменим файл styles.css:

styles.css
css
div[class^='card-'] {
    padding: 10px;
    border: 1px solid #ccc;
}

[attr$="val"]

  • [attr$="val"] - значение оканчивается на val.

Например. Изменим файл index.html:

index.html
html
<body>
    <p data-id="post-123">Пост</p>
    <p data-id="user-456">Пользователь</p>
    <p data-id="123456">Дата</p>
</body>

Изменим файл styles.css:

styles.css
css
p[data-id$='456'] {
    color: blue;
}

[attr*="val"]

  • [attr*="val"] - значение содержит val.

Например. Изменим файл index.html:

index.html
html
<body>
    <span title="important-message">Важное</span>
    <span title="regular-message">Обычное</span>
    <span title="nt-important">Не важное</span>
</body>

Изменим файл styles.css:

styles.css
css
span[title*='mess'] {
    font-weight: bold;
}