#html #css
#HTML #css
Вопрос:
Я нашел другие примеры текста в фоновом режиме, но не анимированного. Я хочу, чтобы он был расположен вот так.
Вот с чем я работаю. https://jsfiddle.net/3esj55rb
.marquee {
color: #333;
padding-left: 1.5em;
position: relative;
font: 50px 'Segoe UI', Tahoma, Helvetica, Sans-Serif;
width: 450px;
margin: 2em auto
overflow: hidden;
white-space: nowrap;
box-sizing: border-box;
animation: marquee 25s linear infinite;
}
.marquee:hover {
color: #F65314;
animation-play-state: paused
}
@keyframes marquee {
0% {
text-indent: 27.5em
}
100% {
text-indent: -105em
}
}
/* Make it pretty */
.microsoft {
padding-left: 1.5em;
position: relative;
font: 50px 'Segoe UI', Tahoma, Helvetica, Sans-Serif;
}
/* ::before was :before before ::before was ::before - kthx */
.microsoft:before,
.microsoft::before {
z-index: 2;
content: '';
position: absolute;
top: -1em;
left: -1em;
width: .5em;
height: .5em;
box-shadow: 1.0em 1.25em 0 #F65314, 1.6em 1.25em 0 #7CBB00, 1.0em 1.85em 0 #00A1F1, 1.6em 1.85em 0 #FFBB00;
}
.microsoft:after,
.microsoft::after {
z-index: 1;
content: '';
position: absolute;
top: 0;
left: 0;
width: 2em;
height: 2em;
background-image: linear-gradient(90deg, white 70%, rgba(255, 255, 255, 0));
}
/* Style the links */
.vanity {
color: #333;
text-align: left;
font: 20px 'Segoe UI', Tahoma, Helvetica, Sans-Serif;
}
.vanity a,
.microsoft a {
color: #1570A6;
transition: color .5s;
text-decoration: none;
}
.vanity a:hover,
.microsoft a:hover {
color: #F65314;
}
.text {
color: #333;
text-align: left;
font: 20px 'Segoe UI', Tahoma, Helvetica, Sans-Serif;
}
.topText {
color: #333;
text-align: left;
font: 20px 'Segoe UI', Tahoma, Helvetica, Sans-Serif;
margin-top: 70px;
}
<p class="topText">
Boston, city, capital of the commonwealth of Massachusetts,
and seat of Suffolk county, in the northeastern United States.
It lies on Massachusetts Bay, an arm of the Atlantic Ocean.
The city proper has an unusually small area for a major city,
and more than one-fourth of the total—including part of the
Charles River, Boston Harbor, and a portion of the Atlantic—is water.
Area city, 46 square miles (119 square km).
</p>
<p class="marquee"> Visit Boston. This text should be in the background</p>
<p class="text">
The area, the people, and the institutions within its political
boundaries can only begin to define the essence of Boston. Its
nickname “Beantown” has its origin in colonial times, when Boston,
as a stop on a major trade route with the West Indies, had a steady
supply of molasses from the Caribbean, thus leading to the creation
of a popular dish that became known as Boston baked beans (beans
baked in molasses).
</p>
<p class="vanity">
Follow us on twitter
<a href="https://twitter.com/boston">@boston</a> to know more.
</p>
<p class="vanity">
Test test
<a href="boston.gov">click here for website</a> or our state's <a href="mass.gov"> mass.gov </a>
</p>
Комментарии:
1. Как ваш текст должен быть анимирован? Вероятно, вам потребуется какое-то абсолютное позиционирование и добавьте анимацию css. Однако, поскольку ваш вопрос в настоящее время стоит, это немного неясно.
2. Он уже анимирован, как в jfiddle. Я просто не могу определить, как разместить его в другом текстовом поле, как на примере изображения.
3. Ах, я приношу извинения, я на мобильном телефоне, возможно, поэтому я не вижу анимацию. Вы пробовали помещать анимированный текст в абсолютно позиционированный контейнер? Вы можете установить для этого индекс z, чтобы убедиться, что он ниже всего остального.
4. Спасибо, выполнение этих двух действий сработало. Я опубликую обновленный фрагмент.
Ответ №1:
Добавлен индекс z и изменено положение относительно контейнера.
.marquee {
color: #333;
padding-left: 1.5em;
font: 50px 'Segoe UI', Tahoma, Helvetica, Sans-Serif;
margin: 2em auto
overflow: hidden;
white-space: nowrap;
box-sizing: border-box;
animation: marquee 10s linear infinite;
z-index: -1;
position: fixed;
width: 450px;
top: 15%;
}
Ответ №2:
С помощью CSS вы можете определить @keyframes, чтобы создавать различные положения, размеры, ангелы и свойства объекта.
для справки:
@keyframes example {
0% {background-color: red;}
25% {background-color: yellow;}
50% {background-color: blue;}
100% {background-color: green;}
}
Здесь вы можете найти ресурсы:https://css-tricks.com/css-techniques-and-effects-for-knockout-text
Ответ №3:
Краткий ответ
Вы должны играть с положением (относительным / абсолютным вместе с верхним). Остерегайтесь упорядочивания дочерних элементов. Кроме того, когда вам нужно остановить анимацию при наведении курсора мыши, убедитесь, что вы помещаете :hover
прослушиватель в соответствующий тег.
Длинный ответ
Ради игры с position я придумал решение. Однако это решение требует дублирования текста.
Идея заключается в следующем:
- A
container
будет содержать три дочерних элемента - Первый дочерний элемент — это первый текст. Он невидим, и его цель — зафиксировать
container
высоту - Второй дочерний элемент — это скользящий текст. С помощью
position: absolute
он должен выравнивать содержимое по вертикали с помощью субконтейнера. - Третий дочерний элемент — это отображаемый текст с абсолютной позицией, а также
Я расширил исходный текст, чтобы убедиться, что мой маркер правильно выровнен по вертикали.
- Минусы
- Текст отображается дважды
- много классов CSS и контейнеров, но это всегда так, не так ли?
- Плюсы
- Вы можете поместить в
.marquee__content
все, что захотите, не толькоp
, но и некоторыеh2
илиh3
или некоторые картинки, все это должно скользить..marquee *{...}
стиль гарантирует, что все дочерние элементы не переносят текст - Более четкое разделение CSS: какой div является тем, что
- Вы можете поместить в
Наконец, код:
/* ========== Container ========== */
/* cosmetic only */
body {
background-color: #cacaca;
}
.container {
/* Required for playing with positions ! */
position: relative;
/* irrelevant: cosmetic only */
width: 60%;
margin: auto;
background: white;
}
/* ========== Text =============== */
/* define all text size so that height fixer can
have the appropriate height */
.text {
/* to ensure both box__text have same height */
font-size: 20px;
/* cosmetic only */
padding: 1rem;
box-sizing: border-box;
}
/* this hack requires an invisible box__text to set
parent div height */
.text--height-fixer {
visibility: hidden;
}
.text--shown {
position: absolute;
/* move to top of parent */
top: 0;
/* take parent width / height */
width: 100%;
height: 100%;
}
/* ========== Marquee ============ */
.marquee {
position: absolute;
/* move to top of parent */
top: 0;
/* take parent width / height */
width: 100%;
height: 100%;
/* hide x overflow for the slide effect */
overflow-x: hidden;
/* vertically align content. I chose display: flex as
I am lazy but this is not the core of the question */
display: flex;
/* cosmetic only */
padding: 1rem;
box-sizing: border-box;
opacity: 0.6;
}
/* force one line layout for all children, not only <p> */
.marquee * {
/* remove line break */
white-space: nowrap;
/* remove all default margin */
margin: auto;
}
/* to match the provided picture */
.marquee .boston {
color: lightblue;
font-size: 4rem;
font-weight: 800;
transition: color 0.2s;
}
@keyframes marquee {
0% {
margin-left: 100%;
}
100% {
margin-left: -100%;
}
}
.marquee__content {
animation: marquee 10s linear infinite;
}
/* this is the tricky part: the "hover" event should not be listened
on marquee but on the container */
.container:hover .marquee__content {
animation-play-state: paused;
}
.container:hover .marquee .boston {
color: orange;
}
<!-- container to manage all positions. Children order matters !-->
<div class="container">
<!-- relative must be first -->
<div class="text text--height-fixer">
<p>
The area, the people, and the institutions within its political boundaries can only begin to define the essence of Boston. Its nickname “Beantown” has its origin in colonial times, when Boston, as a stop on a major trade route with the West Indies, had
a steady supply of molasses from the Caribbean, thus leading to the creation of a popular dish that became known as Boston baked beans (beans baked in molasses). The area, the people, and the institutions within its political boundaries can only
begin to define the essence of Boston. Its nickname “Beantown” has its origin in colonial times, when Boston, as a stop on a major trade route with the West Indies, had a steady supply of molasses from the Caribbean, thus leading to the creation
of a popular dish that became known as Boston baked beans (beans baked in molasses).
</p>
</div>
<!-- marquee should be declared before text so that it appears below without z-index -->
<div class="marquee">
<div class="marquee__content">
<p class="boston">
Visit Boston. This text should be in the background
</p>
</div>
</div>
<div class="text text--shown">
<p>
The area, the people, and the institutions within its political boundaries can only begin to define the essence of Boston. Its nickname “Beantown” has its origin in colonial times, when Boston, as a stop on a major trade route with the West Indies, had
a steady supply of molasses from the Caribbean, thus leading to the creation of a popular dish that became known as Boston baked beans (beans baked in molasses). The area, the people, and the institutions within its political boundaries can only
begin to define the essence of Boston. Its nickname “Beantown” has its origin in colonial times, when Boston, as a stop on a major trade route with the West Indies, had a steady supply of molasses from the Caribbean, thus leading to the creation
of a popular dish that became known as Boston baked beans (beans baked in molasses).
</p>
</div>
</div>
Если у кого-нибудь есть решение получше, которое позволяет отображать любое содержимое marquee (не ограничиваясь одним p
), не стесняйтесь поделиться!