Trang Chủ

“:: after” – “:: before” and things we may not have noticed.

Reading the title, everyone must have guessed today we will talk about the topic ::after and ::before in CSS.

::after and ::before are very familiar to us in the learning and working process, especially the Front End Developer . Today I would like to share a little bit more about what I have learned about these two pseudo-elements, and I hope everyone will support them.

:: after and :: before?

::after and ::before are called pseudo-elements, also known as pseudo-elements and they are used in CSS to create pseudo-elements in element.

::before will create a dummy element which is always the first child of the element used ::before .

The same goes for ::after but the pseudo element is always the last child at this time.

Syntax

In CSS3 we use :: instead of : as in CSS2 with the purpose of distinguishing pseudo-element from pseudo-class.

Some caution when used

first

All browsers support syntax : CSS but for syntax :: in CSS3, we need to pay attention IE8 and Opera only supports 4-6 : . So we should use : instead of :: just concise, make sure there are no unexpected errors. I would like to use : from now until the end of the article.

Monday

Whenever we use :after or :before we need to declare content: ''; for that dummy element, if there is no content then the dummy element will not be rendered in the DOM nor displayed on the website. And content may contain values:

  1. A string: content: 'a string'; . Special characters require special code, such as unicode.
  2. An image: content: url('/path/image.jpg'); . The inserted image will be the same size as the original image and cannot be resized.
  3. Empty: content: ''; Very useful when clearfix and insert the image as background-image
  4. When we want to remove dummy elements from the page, we can use: content: none;

Tuesday

The generated dummy element will have display: inline .

Wednesday

Have you ever tried to add :after or :before for an img tag? Although you have declared the content fully and style everything for it but still do not see :after ( :before ) where even though you check in the dev tool still see.

The reason is that img doesn’t apply :after and :before or it expands that replacing elements won’t apply :after and :before .

So what is the replacement element ? They are elements whose content is outside the scope of CSS formatting models . Or to understand it more simply those elements that CSS cannot style. Including tags such as audio , video , canvas , svg , … You can refer to here

So why is the content of the replacement element out of the scope of the CSS formatting model . Because their content is taken from outside your .html document.

For example, the image you put on the web page with the img will get absolute or relative links in it so its content doesn’t belong to your document.

Chia sẻ bài viết ngay