Pseudo-element Background Reveal on: hover
Резюме
- Целевые устройства (Ширина устройства + 600px - Пожалуйста, игнорировать мобильные /xs экраны)
- Чистый CSS Отображение изображения с помощью
:hover:after
- Работает, но не идеально
- Проблемы:
- соотношение изображения (изображения будут 800 пикселей /600 пикселей) не поддерживается - ширина обрезается, а изображение уменьшается.
- Изображения находятся за пределами основного контейнера
.outercontainer
- затухание изображения на
:hover
работает, но после :hover
<< terminated Я попытался использовать отдельную анимацию/ту же анимацию назад, не повезло
Желаемый эффект:
-
Все вставляется внутри контейнера с синей рамкой, помеченной
.outercontainer
-
Изменить: Изображения должны иметь собственное пространство - около 80% контейнера
ширина и опции/меню будут другими 20% - Нет перекрытия (если изображения перекрываются над опциями, пользователи планшета будут застревать в состоянии зависания)
-
.outercontainer
, и каждый из них настраивается в соответствии с экраном
Ширина
-
Минимальная желаемая ширина устройства для поддержки составляет 600 пикселей (игнорировать экраны размером менее 600 пикселей)
-
Действия:
- Изображения Затухание в
:hover
- Изображения остаются видимыми до тех пор, пока элемет все еще находится в
:hover
- Затухание изображений после того, как элемент "не завис"
Похожие сообщения/проблемы
В SO есть еще много вопросов. Я не нашел тот, который обращается к изображению, являющемуся фоном: после псевдоэлемента
Мои вопросы
-
Как мне поместить изображение, отображаемое с помощью: hover: после внутри родительского контейнера? (Я бы хотел, чтобы он занимал не более 80% -85% от ширины этого контейнера - остальная часть пространства должна быть отнесена к параметрам/пунктам меню/списка)
-
Как я могу сделать изображение, отображаемое с помощью: hover: после реагирования?
-
Как я могу сделать элемент затухающим после того, как его не запустили?
Мои CSS
и HTML
находятся в фрагменте ниже (не полностью resposive - открываются в полноэкранном режиме)
/* Start Miscellaneous stuff */
body {
background: #131418;
color: #999;
text-align: center;
}
.optionlist a {
color: #999;
text-decoration: none;
}
@keyframes mycoolfade {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
/* End Miscellaneous stuff */
.outercontainer {
border: 1px solid blue; /*This needs to be in the middle of the screen and everthing should fit inside it*/
position: fixed; /*border to highlight only - not part of final product*/
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 1200px;
max-width: 80%
}
.optioncontainer {
width: 250px;
max-width: 20vw;
}
.optionlist li {
background: #fff;
padding: .5em;
box-shadow: inset 10px 10px 100px 25px rgba(0, 0, 0, .8);
list-style-type: none;
}
.optionlist li:nth-child(odd) {
background: #000;
}
.optionlist li:hover {
background: red;
}
.optionlist li:hover:after { /* The part the needs to be fixed */
content: '';
width: 800px;
height: 600px;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
animation: mycoolfade 1s;
}
/* Start Background Control */
#red:after {background: url(http://lorempixel.com/800/600/)}
#blue:after {background: url(http://lorempixel.com/800/601/)}
#green:after {background: url(http://lorempixel.com/801/600/)}
#yellow:after {background: url(http://lorempixel.com/801/601/)}
#orange:after {background: url(http://lorempixel.com/799/600/)}
#white:after {background: url(http://lorempixel.com/800/599/)}
#black:after {background: url(http://lorempixel.com/801/599/)}
/* End Background Control */
<body>
The initial hiccup when the images load is not an issue
<div class="outercontainer">
<div class="optioncontainer">
<div class="optionlist">
<li id="red">Red</li>
<li id="blue">Blue</li>
<li id="green">Green</li>
<li id="yellow">Yellow</li>
<li id="orange">Orange</li>
<li id="white">White</li>
<li id="black">Black</li>
</div>
</div>
</div>
</body>
Ответы
Ответ 1
Вот моя попытка
Возможно, я что-то упустил, дайте мне знать, если это так.
Хитрость заключается в том, чтобы ширина элемента optionlist всегда составляла 20% от ширины контейнера.
Таким образом, мы можем сделать псевдоэлементы 400% от их родителя, и это эквивалентно 80%, оставшемуся от контейнера минус список опций.
Чтобы справиться с затуханием, нам нужно постоянно показывать псевдонимы (не только при наведении указателя мыши). Итак, мы объявляем их в базовом состоянии с непрозрачностью 0 и изменяем это на непрозрачность 1 при наведении.
Это приводит к обнаружению ошибки, поскольку наведение на псевдо-триггеры, даже если непрозрачность равна 0, а затем пузырится на элемент. Это можно решить с помощью указателей-событий: ни один из псевдо.
body, html {
height: 100%;
}
body {
background: #131418;
color: #999;
text-align: center;
}
.optionlist a {
color: #999;
text-decoration: none;
}
/* End Miscellaneous stuff */
.outercontainer {
border: 1px solid blue;
/*This needs to be in the middle of the screen t*/
position: relative;
/*border to highlight only - not part of final product*/
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 1200px;
max-width: 80%;
}
.optioncontainer {
width: 20%;
}
.optionlist {
position: relative;
width: 100%;
}
.optionlist li {
background: #fff;
padding: .5em;
box-shadow: inset 10px 10px 100px 25px rgba(0, 0, 0, .8);
list-style-type: none;
}
.optionlist li:nth-child(odd) {
background: #000;
}
.optionlist li:hover {
background: red;
}
.optionlist li:after {
content: '';
width: 400%;
height: 100%;
position: absolute;
top: 0px;
left: 100%;
/*background-size: cover; */
background-position: center;
background-repeat: no-repeat;
opacity: 0;
transition: opacity 1s;
pointer-events: none; /* do not trigger a hover */
}
.optionlist li:hover:after {
opacity: 1;
}
/* Start Background Control */
#red:after {
background-image: url(http://lorempixel.com/800/600/)
}
#blue:after {
background-image: url(http://lorempixel.com/800/601/)
}
#green:after {
background-image: url(http://lorempixel.com/801/600/)
}
#yellow:after {
background-image: url(http://lorempixel.com/801/601/)
}
#orange:after {
background-image: url(http://lorempixel.com/799/600/)
}
#white:after {
background-image: url(http://lorempixel.com/800/599/)
}
#black:after {
background-image: url(http://lorempixel.com/801/599/)
}
<div class="outercontainer">
<div class="optioncontainer">
<div class="optionlist">
<li id="red">Red</li>
<li id="blue">Blue</li>
<li id="green">Green</li>
<li id="yellow">Yellow</li>
<li id="orange">Orange</li>
<li id="white">White</li>
<li id="black">Black</li>
</div>
</div>
</div>
Ответ 2
Просто установите outercontainer
, где хотите. После изменения стиля outercontainer
position
стиль relative
и after
стиль псевдоэлемента на position: absolute; left: 0; top: 0; width: 100%; height: 100%;
кажется, работает нормально, как вы хотите. Используя анимацию CSS, вы можете применить эффект затухания.
============ Последние изменения ==============
Добавлен стиль для outercontainer
, связанный с положением и маркой для отображения его в центре, добавлен стиль псевдоэлемента background
, например no-repeat
и background-size: cover
. Изменена разметка div
до ul
и flex
для ul
.
/* Start Miscellaneous stuff */
body {
background: #131418;
color: #999;
text-align: center;
}
.optionlist a {
color: #999;
text-decoration: none;
}
@keyframes mycoolfade {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
/* End Miscellaneous stuff */
.outercontainer {
border: 1px solid blue; /*This needs to be in the middle of the screen and everthing should fit inside it*/
position: absolute; /*border to highlight only - not part of final product*/
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
min-width: 50%;
min-height: 50%;
width: 80%;
height: 80%;
transform: translate(-50%, -50%);
}
.optioncontainer {
width: 250px;
max-width: 20vw;
height: 100%;
}
.optionlist {
padding: 0;
margin: 0;
display: flex;
flex-direction: column;
height: 100%;
}
.optionlist li {
background: #fff;
padding: .5em;
box-shadow: inset 10px 10px 100px 25px rgba(0, 0, 0, .8);
list-style-type: none;
}
.optionlist li:nth-child(odd) {
background: #000;
}
.optionlist li:hover {
background: red;
}
.optionlist li:hover:after { /* The part the needs to be fixed */
content: '';
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
transform: translate(-50%, -50%);
animation: mycoolfade 1s;
z-index:-1;
}
/* Start Background Control */
#red:after {
background: url(http://lorempixel.com/800/600/) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#blue:after {
background: url(http://lorempixel.com/800/601/) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#green:after {
background: url(http://lorempixel.com/801/600/) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#yellow:after {
background: url(http://lorempixel.com/801/601/) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#orange:after {
background: url(http://lorempixel.com/799/600/) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#white:after {
background: url(http://lorempixel.com/800/599/) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#black:after {
background: url(http://lorempixel.com/801/599/) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
/* End Background Control */
<body>
The initial hiccup when the images load is not an issue
<div class="outercontainer">
<div class="optioncontainer">
<ul class="optionlist">
<li id="red">Red</li>
<li id="blue">Blue</li>
<li id="green">Green</li>
<li id="yellow">Yellow</li>
<li id="orange">Orange</li>
<li id="white">White</li>
<li id="black">Black</li>
</ul>
</div>
</div>
</body>
Ответ 3
Часть fadein/fadeout вашего вопроса:
/* Start Miscellaneous stuff */
body {
background: #131418;
color: #999;
text-align: center;
}
.optionlist a {
color: #999;
text-decoration: none;
}
/* End Miscellaneous stuff */
.outercontainer {
border: 1px solid blue; /*This needs to be in the middle of the screen and everthing should fit inside it*/
position: fixed; /*border to highlight only - not part of final product*/
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 1200px;
max-width: 80%
}
.optioncontainer {
width: 250px;
max-width: 20vw;
}
.optionlist li {
background: #fff;
padding: .5em;
box-shadow: inset 10px 10px 100px 25px rgba(0, 0, 0, .8);
list-style-type: none;
}
.optionlist li:nth-child(odd) {
background: #000;
}
.optionlist li:hover {
background: red;
}
.optionlist li:after {
content: '';
width: 800px;
height: 600px;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
transition: opacity 1s;
opacity: 0;
pointer-events: none;
}
.optionlist li:hover:after {
opacity: 1;
pointer-events: auto;
}
/* Start Background Control */
#red:after {background: url(http://lorempixel.com/800/600/)}
#blue:after {background: url(http://lorempixel.com/800/601/)}
#green:after {background: url(http://lorempixel.com/801/600/)}
#yellow:after {background: url(http://lorempixel.com/801/601/)}
#orange:after {background: url(http://lorempixel.com/799/600/)}
#white:after {background: url(http://lorempixel.com/800/599/)}
#black:after {background: url(http://lorempixel.com/801/599/)}
/* End Background Control */
<body>
The initial hiccup when the images load is not an issue
<div class="outercontainer">
<div class="optioncontainer">
<div class="optionlist">
<li id="red">Red</li>
<li id="blue">Blue</li>
<li id="green">Green</li>
<li id="yellow">Yellow</li>
<li id="orange">Orange</li>
<li id="white">White</li>
<li id="black">Black</li>
</div>
</div>
</div>
</body>
Ответ 4
Хороший вопрос. Я смог добиться этого, используя vh
и vw
единицы для вашего .outercontainer
и немного изменив стили. А именно, перемещение стилей от :hover::after
до ::after
.
.optionlist li:hover::after {
/* Just toggling visibility and setting animation here */
animation: mycoolfadein 1s;
display: block;
}
/* Start Background Control -changed style names for testing */
.listitem::after {
content: "";
width: 80vw;
height: 70vh;
background-image: url(http://lorempixel.com/800/600/);
background-size: 80vw 70vh;
position: fixed;
top: 50%;
left: 50%;
display: none;
transform: translate(-50%, -50%);
}
Что касается требований.
- Как мне поместить изображение, отображаемое с помощью: hover: после внутри родительского контейнера?
- зная ширину родительских контейнеров и устанавливая ее в псевдоэлементе
content
, в этом случае использовали vh и vw и использовали то же самое для размеров изображения
- Как я могу сделать изображение, отображаемое с помощью: hover: после реагирования? - аналогично предыдущему, но вы также можете посмотреть в размер фона, чтобы растянуть изображения на месте.
- Как я могу заставить элемент исчезать после его отмены? - К сожалению, я считаю, что мы должны использовать JS для этого.
Прикрепление скрипта для справки. скрипка здесь
Примечание. Несколько элементов li
будут созданы для нечувствительности для демонстрационных целей.
Другие ссылки для справки, статья CSS-Tricks, SO вопрос о видимости псевдоэлементов
Ответ 5
body {
background: #ccd;
color: #fff;
}
.damn {
width:80%;
height:80%;
border: 1px solid black;
position:absolute;
top:50%;
left: 50%;
transform: translate(-50%, -50%);
display:flex;
align-items:center;
justify-content:center;
}
.controller{
padding:0;
margin:0;
list-style:none;
width:100%;
height:100%;
display:flex;
flex-direction:column;
flex-Wrap:wrap;
align-items:center;
justify-content:center;
}
.controller li {
background: #ddd;
list-style-type: none;
width:20%;
}
.controller li:nth-child(odd) {
background: #000;
}
.controller li:hover {
background: red;
}
.controller li:last-child{
background:#ccc;
width:80%;
height:100%;
padding:1%;}
/* content Control */
.imgWrap{
border:1px solid blue;
display:flex;
overflow:hidden;
align-items:center;
justify-content:center;
}
#red:hover~.imgWrap{
content:url("http://www.markgray.com.au/images/gallery/large/desert-light.jpg");
}
#blue:hover~.imgWrap {
content:url("https://www.hlf.org.uk/sites/default/files/styles/siftgroups_media_fullsize/public/media/programmes/landscape_partnerships_overlooking_the_wye_.jpg?itok=HOgiVAEW&width=800&height=600")}
#green:hover~.imgWrap { content:url("http://www.markgray.com.au/images/gallery/large/desert-light.jpg");
}
#yellow:hover~.imgWrap {
content:url("https://www.hlf.org.uk/sites/default/files/styles/siftgroups_media_fullsize/public/media/programmes/landscape_partnerships_overlooking_the_wye_.jpg?itok=HOgiVAEW&width=800&height=600")}
#orange:hover~.imgWrap { content:url("http://www.markgray.com.au/images/gallery/large/desert-light.jpg");
}
#white:hover~.imgWrap {
content:url("https://www.hlf.org.uk/sites/default/files/styles/siftgroups_media_fullsize/public/media/programmes/landscape_partnerships_overlooking_the_wye_.jpg?itok=HOgiVAEW&width=800&height=600")}
#black:hover~.imgWrap { content:url("http://www.markgray.com.au/images/gallery/large/desert-light.jpg");
}
<body>
<div class="damn">
<ul class="controller">
<li id="red">Red</li>
<li id="blue">Blue</li>
<li id="green">Green</li>
<li id="yellow">Yellow</li>
<li id="orange">Orange</li>
<li id="white">White</li>
<li id="black">Black</li>
<li id="showImg" class="imgWrap">a</li>
</ul>
</div>
</body>