Псевдоэлементы

CSS Свойства

align-contentalign-itemsalign-selfallanimationanimation-delayanimation-directionanimation-durationanimation-fill-modeanimation-iteration-countanimation-nameanimation-play-stateanimation-timing-functionbackface-visibilitybackgroundbackground-attachmentbackground-blend-modebackground-clipbackground-colorbackground-imagebackground-originbackground-positionbackground-repeatbackground-sizeborderborder-bottomborder-bottom-colorborder-bottom-left-radiusborder-bottom-right-radiusborder-bottom-styleborder-bottom-widthborder-collapseborder-colorborder-imageborder-image-outsetborder-image-repeatborder-image-sliceborder-image-sourceborder-image-widthborder-leftborder-left-colorborder-left-styleborder-left-widthborder-radiusborder-rightborder-right-colorborder-right-styleborder-right-widthborder-spacingborder-styleborder-topborder-top-colorborder-top-left-radiusborder-top-right-radiusborder-top-styleborder-top-widthborder-widthbottombox-decoration-breakbox-shadowbox-sizingcaption-sidecaret-color@charsetclearclipcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-weightgridgrid-areagrid-auto-columnsgrid-auto-flowgrid-auto-rowsgrid-columngrid-column-endgrid-column-gapgrid-column-startgrid-gapgrid-rowgrid-row-endgrid-row-gapgrid-row-startgrid-templategrid-template-areasgrid-template-columnsgrid-template-rowshanging-punctuationheighthyphens@importisolationjustify-content@keyframesleftletter-spacingline-heightlist-stylelist-style-imagelist-style-positionlist-style-typemarginmargin-bottommargin-leftmargin-rightmargin-topmax-heightmax-width@mediamin-heightmin-widthmix-blend-modeobject-fitobject-positionopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-xoverflow-ypaddingpadding-bottompadding-leftpadding-rightpadding-toppage-break-afterpage-break-beforepage-break-insideperspectiveperspective-originpointer-eventspositionquotesresizerighttab-sizetable-layouttext-aligntext-align-lasttext-decorationtext-decoration-colortext-decoration-linetext-decoration-styletext-indenttext-justifytext-overflowtext-shadowtext-transformtoptransformtransform-origintransform-styletransitiontransition-delaytransition-durationtransition-propertytransition-timing-functionunicode-bidiuser-selectvertical-alignvisibilitywhite-spacewidthword-breakword-spacingword-wrapwriting-modez-index

CSS Properties

align-contentalign-itemsalign-selfallanimationanimation-delayanimation-directionanimation-durationanimation-fill-modeanimation-iteration-countanimation-nameanimation-play-stateanimation-timing-functionbackface-visibilitybackgroundbackground-attachmentbackground-blend-modebackground-clipbackground-colorbackground-imagebackground-originbackground-positionbackground-repeatbackground-sizeborderborder-bottomborder-bottom-colorborder-bottom-left-radiusborder-bottom-right-radiusborder-bottom-styleborder-bottom-widthborder-collapseborder-colorborder-imageborder-image-outsetborder-image-repeatborder-image-sliceborder-image-sourceborder-image-widthborder-leftborder-left-colorborder-left-styleborder-left-widthborder-radiusborder-rightborder-right-colorborder-right-styleborder-right-widthborder-spacingborder-styleborder-topborder-top-colorborder-top-left-radiusborder-top-right-radiusborder-top-styleborder-top-widthborder-widthbottombox-decoration-breakbox-shadowbox-sizingbreak-afterbreak-beforebreak-insidecaption-sidecaret-color@charsetclearclipclip-pathcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-feature-settingsfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-variant-capsfont-weightgapgridgrid-areagrid-auto-columnsgrid-auto-flowgrid-auto-rowsgrid-columngrid-column-endgrid-column-gapgrid-column-startgrid-gapgrid-rowgrid-row-endgrid-row-gapgrid-row-startgrid-templategrid-template-areasgrid-template-columnsgrid-template-rowshanging-punctuationheighthyphens@importisolationjustify-content@keyframesleftletter-spacingline-heightlist-stylelist-style-imagelist-style-positionlist-style-typemarginmargin-bottommargin-leftmargin-rightmargin-topmax-heightmax-width@mediamin-heightmin-widthmix-blend-modeobject-fitobject-positionopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-xoverflow-ypaddingpadding-bottompadding-leftpadding-rightpadding-toppage-break-afterpage-break-beforepage-break-insideperspectiveperspective-originpointer-eventspositionquotesresizerightrow-gapscroll-behaviortab-sizetable-layouttext-aligntext-align-lasttext-decorationtext-decoration-colortext-decoration-linetext-decoration-styletext-indenttext-justifytext-overflowtext-shadowtext-transformtoptransformtransform-origintransform-styletransitiontransition-delaytransition-durationtransition-propertytransition-timing-functionunicode-bidiuser-selectvertical-alignvisibilitywhite-spacewidthword-breakword-spacingword-wrapwriting-modez-index

Placing after and before at the beginning of a clause

Clause Position

INITIAL POSITION / FRONTED PHRASE

A connective prepositional phrase can be moved in front of the main clause for emphasis. A comma is placed after it.

FRONTED PHRASE— COMMA

As soon as you get here, we’ll leave.

Before I drink coffee, my head hurts.

After I drink coffee, my headache stops.

When you give me the keys, I’ll start driving.

FINAL POSITION

No comma is used when the connective prepositional phrase is placed after the main clause.

PHRASE IN NORMAL POSITION — NO COMMA

We’ll leave as soon as you get here.

My head hurts before I drink coffee.

My headache stops after I drink coffee.

I’ll start driving when you give me the keys.

Adjunct – add on structure; the connective preposition adds a clause that is not required by the main clause to make sense.

Prepositional Phrase =    See

Особенности псевдоэлементов before и after

  1. 1.Псевдоэлементы должны указываться сразу после селектора через двойное двоеточие без пробела, как показано в примерах выше. Однако допускается и использование одинарного двоеточия.

    PHP

    .block-class:before

    1 .block-classbefore
  2. 2.Псевдоэлемет является строчным элементом, поэтому если в CSS свойстве content ничего не указано то его ширина по умолчанию будет равна нулю. Так же для строчных элементов не применяется вертикальные отступы margin. Чтобы они начали работать и элемент стал на всю ширину ему нужно дописать CSS свойство display:block;
  3. 3.Вы можете использовать только один псевдоэлемент на селектор. То есть нельзя использовать сразу 2 псевдоэлемента для одного блока.
    Запись .block-class::before::after или #content::first-line::after будет неправильной.
  4. 4.Кроме псевдоэлементов ::before и ::after существуют и другие, такие как ::selection, ::first-line, ::first-letter, о которых я расскажу в одной из следующих статей.

Спасибо что посетили мой сайт!

С уважением Юлия Гусарь

Вставка содержимого без изменения файлов шаблонов для сайта WordPress

Для сайтов WordPress также можно использовать псевдоэлементы. Например, если нужно добавить уведомление о доставке в заголовке на каждой странице, но установленная тема не позволяет что-то добавить, кроме строки поиска и корзины. Это гораздо проще, чем переделывать шаблон. Добавив псевдоэлемент :after и нужную надпись в свойство “content”, можно расположить ее на удобном месте, где она будет смотреться логично. Главным выводом из этого является то, что использование :before и :after настолько широко, что позволяет по-разному позиционировать элементы, заставляя их находиться справа или слева от контейнера, использовать поля и отступы.

CSS Properties

align-contentalign-itemsalign-selfallanimationanimation-delayanimation-directionanimation-durationanimation-fill-modeanimation-iteration-countanimation-nameanimation-play-stateanimation-timing-functionbackface-visibilitybackgroundbackground-attachmentbackground-blend-modebackground-clipbackground-colorbackground-imagebackground-originbackground-positionbackground-repeatbackground-sizeborderborder-bottomborder-bottom-colorborder-bottom-left-radiusborder-bottom-right-radiusborder-bottom-styleborder-bottom-widthborder-collapseborder-colorborder-imageborder-image-outsetborder-image-repeatborder-image-sliceborder-image-sourceborder-image-widthborder-leftborder-left-colorborder-left-styleborder-left-widthborder-radiusborder-rightborder-right-colorborder-right-styleborder-right-widthborder-spacingborder-styleborder-topborder-top-colorborder-top-left-radiusborder-top-right-radiusborder-top-styleborder-top-widthborder-widthbottombox-decoration-breakbox-shadowbox-sizingbreak-afterbreak-beforebreak-insidecaption-sidecaret-color@charsetclearclipclip-pathcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-feature-settingsfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-variant-capsfont-weightgapgridgrid-areagrid-auto-columnsgrid-auto-flowgrid-auto-rowsgrid-columngrid-column-endgrid-column-gapgrid-column-startgrid-gapgrid-rowgrid-row-endgrid-row-gapgrid-row-startgrid-templategrid-template-areasgrid-template-columnsgrid-template-rowshanging-punctuationheighthyphens@importisolationjustify-content@keyframesleftletter-spacingline-heightlist-stylelist-style-imagelist-style-positionlist-style-typemarginmargin-bottommargin-leftmargin-rightmargin-topmax-heightmax-width@mediamin-heightmin-widthmix-blend-modeobject-fitobject-positionopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-xoverflow-ypaddingpadding-bottompadding-leftpadding-rightpadding-toppage-break-afterpage-break-beforepage-break-insideperspectiveperspective-originpointer-eventspositionquotesresizerightrow-gapscroll-behaviortab-sizetable-layouttext-aligntext-align-lasttext-decorationtext-decoration-colortext-decoration-linetext-decoration-styletext-indenttext-justifytext-overflowtext-shadowtext-transformtoptransformtransform-origintransform-styletransitiontransition-delaytransition-durationtransition-propertytransition-timing-functionunicode-bidiuser-selectvertical-alignvisibilitywhite-spacewidthword-breakword-spacingword-wrapwriting-modez-index

Метод 5: Псевдоэлементы с наложением цвета при наведении

Одна из последних тенденций в графическом дизайне — эффекта наложения цвета при наведении. Для этого можно использовать псевдоэлементы:

Пример

Код HTML:

<ul>
   <li>
      <img alt="Image" src="images/thumb.jpeg">
      <p>Lorem Ipsum</p>
   </li>
   <li>
     <img alt="Image" src="images/thumb.jpeg">
     <p>Lorem Ipsum</p>
   </li>
</ul>

Код li active CSS:

ul li                { width: 49%; padding: 0 5px; display: inline-block; text-align: center; position: relative;}
ul li img            { max-width: 100%; height: auto;}
ul li p              { margin: 0; padding: 20px; background: #ffffff;}
ul li::after         { height: 100%; content: ""; background: rgba(0,0,0,0.8); position: absolute; top: 0; left: 5px; right: 5px; opacity: 0;}
ul li:hover::after,
ul li:hover::before  { opacity: 1; cursor: pointer;}
ul li::before        { content: "Hover Text"; position: absolute; top: calc(50% - 12px); left: calc(50% - 40px); color: #ffffff; opacity: 0; z-index: 10;}

Результат:

hover active CSS

Данная публикация является переводом статьи «5 CSS3 TRICKS WITH PSEUDO ELEMENTS BEFORE AND AFTER» , подготовленная редакцией проекта.

Пример использования

<!DOCTYPE html>
<html>
	<head>
		<title>Использование jQuery метода .before() (добавление элемента)</title>
		<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
		<script>
	$( document ).ready(function(){
	  $( "p:first" ).before( "<b>Hello world!</b>" ); // добавляем содержимое перед первым элементом <p> в документе
	});
		</script>
	</head>
	<body>
		<p>Первый абзац</p>
		<p>Второй абзац</p>
	</body>
</html>

В этом примере с использованием jQuery метода .before() мы добавляем перед первым элементом <p> в документе текстовое содержимое, заключенное в элемент <b> (жирное начертание текста).

Результат нашего примера:

Пример использования jQuery метода .before() (добавление элемента)

В следующем примере мы рассмотрим как передать методу .before() несколько параметров.

<!DOCTYPE html>
<html>
	<head>
		<title>Использование jQuery метода .before() (добавление нескольких элементов)</title>
		<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
		<script>
	$( document ).ready(function(){
	  var h3 ="<h3>Заголовок третьего уровня</h3>", // создаем две переменные
	      hr = document.createElement( "hr" ); // создаем элемент <hr> и помещаем в переменную
	  $( "p:first" ).before( "<b>Hello world!</b>", ["<h2>Заголовок второго уровня</h2>", h3, hr] ); // добавляем содержимое перед первым элементом <p> в документе
	});
		</script>
	</head>
	<body>
		<p>Первый абзац</p>
		<p>Второй абзац</p>
	</body>
</html>

В этом примере с использованием jQuery метода .before() мы добавляем перед первым элементом

несколько различных элементов

Обращаю Ваше внимание, что метод .before() может принимать любое количество аргументов и следующая запись будет делать тоже самое, что и запись рассмотренная в примере:

$( "p:first" ).before( "<b>Hello world!</b>", "<h2>Заголовок второго уровня</h2>", h3, hr ); // допускается передавать параметры не в массиве

Результат нашего примера:

Пример использования jQuery метода .before() (добавление нескольких элементов)

В следующем примере мы в качестве параметра метода .before() передадим jQuery объект.

<!DOCTYPE html>
<html>
	<head>
		<title>Использование jQuery метода .before() (передача jQuery объекта)</title>
		<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
		<script>
	$( document ).ready(function(){
	  $( ".first" ).before( $( ".third" ) ); // перемещаем содержимое перед элементом с классом .first
	});
		</script>
	</head>
	<body>
		<ul>
			<li class = "first">1</p>
			<li class = "second">2</p>
			<li class = "third">3</p>
		</ul>
	</body>
</html>

В этом примере с использованием jQuery метода .before() мы добавляем перед элементом

с классом «first» элемент
с классом «third»Обратите внимание, что при этом элемент не клонируется, а перемещается

Результат нашего примера:

Пример использования jQuery метода .before() (передача jQuery объекта)

В следующем примере мы в качестве параметра метода .before() передадим функцию.

<!DOCTYPE html>
<html>
	<head>
		<title>Использование jQuery метода .before() (использование функции)</title>
		<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
		<script>
	$( document ).ready(function(){
	  $( "p:first" ).before(function( index, html ){
            return "<ul><li>Индекс элемента: " + index + "</li><li>Содержимое элемента: " + html + "</li></ul>";
	  });
	});
		</script>
	</head>
	<body>
		<p>Первый абзац</p>
		<p>Второй абзац</p>
	</body>
</html>

В этом примере с использованием jQuery метода .before() и функции, переданной в качестве параметра метода, мы выводим после каждого элемента <p> в документе маркированный список (<ul>), который содержит информацию о индексе элемента и его содержимом.

Результат нашего примера:

Пример использования jQuery метода .before() (использование функции)jQuery DOM методы

Пример использования

Рассмотрим пример, в котором после каждого блока с изображением и после каждого абзаца будет генерироваться (добавляться) определенная фраза:


Пример использования псевдоэлемента ::after

Нет

Да

В этом примере мы указали фиксированную ширину для всех изображений (ширина и высота 100 пикселей). Кроме того, мы выбрали все элементы <div> с классом omg и добавили после них определенную фразу. После абзацев (элементы <p>) также добавляется определенная фраза.

Обращаю Ваше внимание, что к таким элементам как и напрямую псевдоэлемент ::after применить нельзя. Один из выходов из этой ситуации – заключить элемент в блочный элемент

Результат нашего примера:

Пример использования псевдоэлемента ::after.

Выведем содержание, как значение атрибута элемента, использую псевдоэлемент :after и свойство content:

<!DOCTYPE html>
<html>
<head>
<title>Пример использования счетчиков в CSS.</title>
<style> 
a:after {/* Псевдоэлемент :after добавляет содержимое, указанное в свойстве content после каждого элемента <а> */
content : ""attr(title)""; /* между всеми тегами <a></a> автоматически будет проставляться значение атрибута title */
}
</style>
</head>
<body>
<a href = "http://basicweb.ru" title = "Basicweb.ru"></a>
</body>
</html>

Пример добавления и изменения кавычек в тексте, используя CSS свойства content, quotes, а также псевдоэлементов :before и :after:

<!DOCTYPE html>
<html>
<head>
<title>Пример добавления кавычек к тексту в CSS</title>
<style> 
* {
quotes : "«" "»" "‹" "›"; /* используя универсальный селектор устанавливаем тип кавычек для первого и второго уровня вложенности (для всех элементов) */
}
p:before {content : open-quote;}  /* используя псевдоэлемент :before добавляем перед элементом <p> открывающиеся кавычки */
p:after {content : close-quote;}  /* используя псевдоэлемент :after добавляем после элемента <p> закрывающиеся кавычки */
</style>
</head>
<body>
<q>Обычная цитата<q>
<q>Это <q>ЦИТАТА</q> внутри цитаты</q>
<p>Параграф, к которому, используя псевдоклассы добавлены кавычки.</p>
</body>
</html>

Пример добавления и изменения кавычек в тексте.CSS селекторы

Before или beforehand?

Следует обратить внимание на часть речи, к которой относится каждое из слов. Ведь именно это определяет место слова в предложении, его функцию и перевод

Однако в английском языке одно и то же слово может выступать несколькими частями речи в зависимости от ситуации.

Before

Из таблицы вы узнаете, когда before выступает наречием, союзом и предлогом.

Вопрос Часть речи Значение Пример
когда? предлог перед, до She always goes jogging before breakfast. – Она всегда бегает перед завтраком.

I should have told you about it before the trip. – Я должен был рассказать тебе об этом перед поездкой.

где? предлог перед, впереди You didn’t stand before me in the queue. – Вы не стояли передо мной в очереди.
когда? союз прежде чем, до того как Give me a call before you leave. – Позвони мне до того, как уйдешь.

Before you go to sleep, please switch off the TV. – Прежде чем идти спать, пожалуйста, выключи телевизор.

когда? наречие раньше, прежде I could learn poems quickly before. – Раньше я мог быстро учить стихи.

I should have told you about it before. – Я должен был рассказать тебе об этом раньше.

Обратите внимание, когда слово before выступает в роли наречия, оно стоит в конце предложения, предлога – в середине, а союза – в начале или в середине предложения

Beforehand

Теперь рассмотрим слово beforehand. Оно выступает только наречием и всегда стоит в конце предложения.

Вопрос Часть речи Значение Пример
когда?, как? наречие заранее, заблаговременно Make your payments beforehand. Thus, you can avoid potential problems. – Вносите оплату заблаговременно. Так вы сможете избежать возможных проблем.

I should have told you about it beforehand. – Я должен был рассказать тебе об этом заранее.

Многие путают before и beforehand. Несмотря на то, что они оба используются как наречия, они различаются по значению.

Практическое применение :before и :after в CSS

Наверное, самое популярное использование данных псевдоэлементов — добавление иконок. В этом случае они будут располагаться до или после какого-то текста, например, названия компании. Еще один вариант применения — стилизация заголовков. Но псевдоэлементы можно использовать не только для создания разнообразных украшений на странице. Рассмотрим очень распространенный пример: красную звездочку, которая находится в поле формы, обязательном для заполнения. Один из простых способов это сделать — размещать ее каждый раз непосредственно в HTML-разметке. Но ради этого придется писать очень много разметки для одной красной звездочки. Кроме того, что если мы хотим изменить все эти звездочки в точки или в слова или перекрасить их в другой цвет? В этом случае придется сделать одно и то же изменение в каждом из дубликатов.

Traditional and Linguistic Descriptions

Traditional and Linguistic Descriptions

TRADITIONAL GRAMMAR

In traditional grammar, while, when, before, after, and since are conjunctions which join an adverb clause to an independent clause. The term adverbial clause is used because the clause adds time-related information about the verb and answers the question When? This added-on structure is called a dependent clause because it can not stand alone as a sentence.

Azar & Hagen call these structures adverbial clauses or «time clauses» with no mention of a term for the connector. It is not clear whether while, when, before, after, and since are adverbs or conjunctions. «A time clause begins with such words as when, before after, as soon as, until, and while and includes a subjects and a verb.  The time clause can come either at the beginning of the sentence or in the second part of the sentence…»

(Azar 4-3, Adverb clauses 17-2; Reduction  18-1)

after, because, though, if— adverb clauses  (Azar 17.3-11)

PARSED / LINEAR DIAGRAM
LINGUISTIC DESCRIPTIONS

In current linguistic analysis – while, when, before, after, and since — are prepositions which take a clause as their complement: a finite clause (while we were walking home) or a nonfinite gerund-participle clause (while walking home).  Before and after additionally take a noun complement (before me).  The structure is called an adjunct because it is not required to complete the meaning of the sentence. (The clause can be considered complete without the prepositional phrase.)

Huddleston & Pullum (2009) use the term «temporal location expressions». In their grammar description, they reassign a large number of items previously analyzed as adverbs after, as, as soon as, before, once, since while, and when to the category of Prepositions.  The preposition is the head of the prepositional phrase (PP) which can be complemented by a noun phrase or a clause (with a subject and a verb, or a clause with a ).  (7.2.4, 8.63)

Swan (2009) refers to while, when, before, after, and since as conjunctions. (29.1, 30.1, 73, 97, 411.6, 510)

after, before, since, when, while 
— temporal location adjuncts.prepositions  (Huddleston 7.2.4, 8 §6.3)
— conjunctions (Swan 29.1, 30.1, 73, 97, 411.6, 510)
— subordinator. adverbial clause (Biber 2.4.7.5)
— subordinator. adverbial clause (Biber 8.53, 15.28)

TREE DIAGRAM

N – Noun; V – Verb; Aux – Auxiliary; Adj – Adjective; Adv – Adverb; P –Preposition; Det –Determiner.

NP – Noun Phrase; VP – Verb Phrase; AdjP – Adjective Phrase; AdvP – Adverb Phrase; PP – Prepositional Phrase; DP – Determinative Phrase.

Clausal Categories: Cls – clause; F – finite clause; NF – nonfinite clause (Ger – gerund; Inf – infinitive; PPart – past participle).

Word Functions: Subj – subject; Pred – predicate/predicator; Comp – : elements required by an expression to complete its meaning (DO – direct object; IO – indirect object);  Adjunct – elements not required by an expression to complete its meaning (Subord – subordinator; Coord – coordinator); Supl – : a clause or phrase added onto a clause that is not closely related to the central thought or structure of the main clause.

A Changed Opinion

Read for Errors

awful (Adj) — unpleasant, bad

bachelor’s degree (N) — a certificate of completion for four years of college of university study

exaggerate (V) — describe as better, worse or larger than something really is

fearful (Adj) — afraid; a preoccupation of danger

mixture (N) — combination; a mix of different things

neighborhood (N) — the area or region around or near some place or thing; vicinity

opinion (N) — personal view, attitude, judgment

pleasantly (adv.) — pleasing, agreeable, enjoyable

Edit for Errors

  1. Edit the sentence(s) in the text box.
  2. Compare your response to the feedback by clicking the «Check» or the «Check 21-30» button.

CSS — The ::selection Pseudo-element

The pseudo-element matches the portion of an element that is
selected by a user.

The following CSS properties can be applied to :
,
, , and .

The following example makes the selected text red on a yellow background:

Example

::selection {  color: red;  
background: yellow;}

All CSS Pseudo Elements

Selector Example Example description
::after p::after Insert something after the content of each <p> element
::before p::before Insert something before the content of each <p> element
::first-letter p::first-letter Selects the first letter of each <p> element
::first-line p::first-line Selects the first line of each <p> element
::marker ::marker Selects the markers of list items
::selection p::selection Selects the portion of an element that is selected by a user

All CSS Pseudo Classes

Selector Example Example description
:active a:active Selects the active link
:checked input:checked Selects every checked <input> element
:disabled input:disabled Selects every disabled <input> element
:empty p:empty Selects every <p> element that has no children
:enabled input:enabled Selects every enabled <input> element
:first-child p:first-child Selects every <p> elements that is the first child of its parent
:first-of-type p:first-of-type Selects every <p> element that is the first <p> element of its parent
:focus input:focus Selects the <input> element that has focus
:hover a:hover Selects links on mouse over
:in-range input:in-range Selects <input> elements with a value within a specified range
:invalid input:invalid Selects all <input> elements with an invalid value
:lang(language) p:lang(it) Selects every <p> element with a lang attribute value starting with «it»
:last-child p:last-child Selects every <p> elements that is the last child of its parent
:last-of-type p:last-of-type Selects every <p> element that is the last <p> element of its parent
:link a:link Selects all unvisited links
:not(selector) :not(p) Selects every element that is not a <p> element
:nth-child(n) p:nth-child(2) Selects every <p> element that is the second child of its parent
:nth-last-child(n) p:nth-last-child(2) Selects every <p> element that is the second child of its parent, counting from the last child
:nth-last-of-type(n) p:nth-last-of-type(2) Selects every <p> element that is the second <p> element of its parent, counting from the last child
:nth-of-type(n) p:nth-of-type(2) Selects every <p> element that is the second <p> element of its parent
:only-of-type p:only-of-type Selects every <p> element that is the only <p> element of its parent
:only-child p:only-child Selects every <p> element that is the only child of its parent
:optional input:optional Selects <input> elements with no «required» attribute
:out-of-range input:out-of-range Selects <input> elements with a value outside a specified range
:read-only input:read-only Selects <input> elements with a «readonly» attribute specified
:read-write input:read-write Selects <input> elements with no «readonly» attribute
:required input:required Selects <input> elements with a «required» attribute specified
:root root Selects the document’s root element
:target #news:target Selects the current active #news element (clicked on a URL containing that anchor name)
:valid input:valid Selects all <input> elements with a valid value
:visited a:visited Selects all visited links

❮ Previous
Next ❯

Bonus step: Advanced overlays with blend modes

I’ve been toying with background blend modes for a little while now, but it blew me away when I discovered . This allows a developer to blend multiple elements together!

Use on your overlay and you’ve got some fun new combinations to try out.

The support for various blend modes are pretty weak in the Microsoft browsers, but you can still use them today with clever progressive enhancement. If you want them to be built in Edge, you can let Microsoft know about your passion here.

Until that time, let’s use queries to make sure our code still respects our friends using Edge and IE. The above code removes the transparency from our overlay and lets the blend mode do it for us. Instead of removing it, let’s negate it behind a support query.

This way in browsers that don’t support blend modes, we get our average, but nice overlay and in browsers that do, we get some really neat effects on our banner.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector