Html css before img

Популярно о псевдоэлементах :Before и :After

Псевдоэлементы :before и :after позволяют добавлять содержимое (стили) до и после элемента, к которому были применены.

Всего существует несколько типов псевдоэлементов: :first-line, :first-letter, ::selection, :before и :after. В этой статье подробно рассмотрены последние два, как наиболее полезные.

Синтаксис и поддержка браузерами

Псевдоэлементы появились еще в CSS1, но пошли в релиз только в CSS2.1. В самом начале в синтаксисе использовалось одно двоеточие, но в CSS3 используется двойное двоеточие для отличия от псевдоклассов:

Но в любом случае, современные браузеры умеют понимать оба типа синтаксиса псевдоэлементов, кроме Internet Explorer 8, который воспринимает только одно двоеточие. Поэтому надежнее использовать одно.

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

 

:before Это основной контент. :after

Элементы :before и :after не будут сгенерированы, т.е. не будут видны в коде страницы, поэтому они и называются псевдоэлементами.

Использование

Использовать псевдоэлементы крайне просто: :before добавляется перед нужным элементом, а :after — после.
Для добавление контента внутри псевдоэлементов можно воспользоваться CSS-свойством content.

Простой пример: необходимо добавить кавычки для цитаты:

blockquote:before < content: open-quote; >blockquote:after

Стилизация псевдоэлементов

К псевдоэлементом можно применять такие же стили, как и к «реальным»: изменение цвета, добавление фона, регулировка размера шрифта, выравнивание текста и т.д.

blockquote:before < content: open-quote; font-size: 24pt; text-align: center; line-height: 42px; color: #fff; background: #ddd; float: left; position: relative; top: 30px; >blockquote:after

Созданные элементы по умолчанию inline-элементы, поэтому при указании высоты или ширины необходимо установить display: block:

blockquote:before < content: open-quote; font-size: 24pt; text-align: center; line-height: 42px; color: #fff; background: #ddd; float: left; position: relative; top: 30px; border-radius: 25px; /** define it as a block element **/ display: block; height: 25px; width: 25px; >blockquote:after < content: close-quote; font-size: 24pt; text-align: center; line-height: 42px; color: #fff; background: #ddd; float: rightright; position: relative; bottombottom: 40px; border-radius: 25px; /** define it as a block element **/ display: block; height: 25px; width: 25px; >

Также внутри псевдоэлемента можно использовать картинку вместо обычного текста, и даже добавлять фоновое изображение.

Читайте также:  Try except python traceback

blockquote:before < content: " "; font-size: 24pt; text-align: center; line-height: 42px; color: #fff; float: left; position: relative; top: 30px; border-radius: 25px; background: url(images/quotationmark.png) -3px -3px #ddd; display: block; height: 25px; width: 25px; >blockquote:after < content: " "; font-size: 24pt; text-align: center; line-height: 42px; color: #fff; float: rightright; position: relative; bottombottom: 40px; border-radius: 25px; background: url(images/quotationmark.png) -1px -32px #ddd; display: block; height: 25px; width: 25px; >

В этом примере свойство content содержит пустую строку, это необходимо, иначе псевдоэлемент не будет правильно отображаться.

Использование вместе с псевдоклассами

Псевдоэлементы могут быть использованы вместе с псевдоклассами, в нашем примере это поможет добавить hover-эффект кавычкам:

blockquote:hover:after, blockquote:hover:before

Добавление transition-эффекта

Также можно применить свойство transition для плавного изменения цвета кавычек:

transition: all 350ms; -o-transition: all 350ms; -moz-transition: all 350ms; -webkit-transition: all 350ms; 

К сожалению, это нормально работает только в последних версиях Firefox.

Посмотреть демонстрацию примера из этой статьи.

Немного вдохновения

Три примера использования псевдоэлементов :before и :afte:

Источник

Using :before CSS pseudo element to add image to modal

I have a CSS class Modal which is absolutely positioned, z-indexed above it’s parent, and nicely positioned with JQuery. I want to add a caret image (^) to the top of the modal box and was looking at using the :before CSS pseudo selector to do this cleanly. The image needs to be absolutely positioned and z-indexed above the modal, but I haven’t found any way to add the appropriate class to the image in the content attribute:

4 Answers 4

::after and ::before with content are better to use as they’re supported in every major browser other than Internet Explorer at least 5 versions back. Internet Explorer has complete support in version 9+ and partial support in version 8.

Читайте также:  Css div inline block right

Is this what you’re looking for?

If not, can you explain a little better?

or you could use jQuery, like Joshua said:

$(«.Modal»).before(«»);

This. Joshua’s point about browser compatibility is also right though- IE8 renders the image in the :after content, but won’t render the parts of it which are outside the parent’s border.

Now (in 2017), IE 11 is the only version of IE still supported by Microsoft; so, there is not much point in worrying about IE8 compatability. Also, a CSS solution is almost always better than the jQuery solution because they tend to load much faster and jQuery can cause screen flicker by rewriting your layout after the page is loaded.

You should use the background attribute to give an image to that element, and I would use ::after instead of before, this way it should be already drawn on top of your element.

Thanks for the suggestion- the modal has a border so I don’t think I can use background image to position the carrot image above the border / bg color as needed.

Why not? if you absolutely position that pseudo element you can move it around with margins. It will be drawn on top of the other element borders and/or bg color.

the display:block is important, I was copying over the style which was given to a normal div earlier. It didn’t have display:block, mine worked only after adding display:block

1.this is my answer for your problem.

Content and before are both highly unreliable across browsers. I would suggest sticking with jQuery to accomplish this. I’m not sure what you’re doing to figure out if this carrot needs to be added or not, but you should get the overall idea:

$(".Modal").before(""); 

This makes me sad. We’ve got a mercifully limited set of targetted browsers, so I’m still interested in what’s possible with CSS.

Читайте также:  What are HTML imports and how do they work

Even with content being heavily used in CSS3, from what I’ve seen it’s still one of those that aren’t fully supported anywhere. I believe this has to do with some fear of being able to inject evil things. Also, I believe content needs an already existing element to inject to — not sure if I can manipulate the DOM that much on it’s own.

This answer is wrong about it having unreliable support across browsers. Content and after/before are very reliable across every single major browser, it’s worked since ie8, at least FF3.5, at least Chrome 9, at least Opera 10.6, at least Safari 3.2, every version of iOS Safari, every version of Opera mini, every version of Opera Mobile, and ever version of the Android browser. if you wanna know if something is supported cross-browser, check out: caniuse.com/#search=:after

Just because the internet says it is, doesn’t mean it’s true. Work with them, they act differently in every browser. And IE 7 is still a very popular browser, which does not support either of them.

Actually, you are better off with CSS over JavaScript on this one. No matter how bleeding edge the browser is, the user can still have JavaScript disabled. Luckily in this case the :before and :after selectors are widely supported; quirksmode.org/css/selectors

Источник

Оцените статью