Reading the title, everyone must have guessed today we will talk about the topic
::before in CSS.
::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?
::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
The same goes for
::after but the pseudo element is always the last child at this time.
<span class="token comment">/* CSS3 syntax */</span>
<span class="token punctuation">:</span> <span class="token punctuation">:</span> after <span class="token comment">/*or ::before*/</span>
<span class="token comment">/* CSS2 syntax */</span>
<span class="token punctuation">:</span> after <span class="token comment">/*or :before*/</span>
In CSS3 we use
:: instead of
: as in CSS2 with the purpose of distinguishing pseudo-element from pseudo-class.
Some caution when used
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.
Whenever we use
: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:
- A string:
content: 'a string';. Special characters require special code, such as unicode.
- An image:
content: url('/path/image.jpg');. The inserted image will be the same size as the original image and cannot be resized.
content: '';Very useful when clearfix and insert the image as
- When we want to remove dummy elements from the page, we can use:
The generated dummy element will have
display: inline .
Have you ever tried to add
:before for an
img tag? Although you have declared the
content fully and style everything for it but still do not see
:before ) where even though you check in the dev tool still see.
The reason is that
img doesn’t apply
:before or it expands that replacing elements won’t apply
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
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
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.
Nguồn bài viết : Viblo