Spec-Zone.ru › CSS

Свойство CSS `offset-anchor`

Базовая поддержка Широко доступно

Эта функция хорошо зарекомендовала себя и работает на многих устройствах и в различных версиях браузеров. Она доступна во всех браузерах с сентября 2022 года.

Свойство offset-anchor CSS задаёт точку внутри блока элемента, перемещающегося вдоль offset-path, которая фактически движется по траектории.

Попробуйте

offset-anchor: auto;
offset-anchor: right top;
offset-anchor: left bottom;
offset-anchor: 20% 80%;
<section class="default-example" id="default-example">
  <div class="wrapper">
    <div id="example-element"></div>
  </div>
  <button id="playback" type="button">Play</button>
</section>
#example-element {
  offset-path: path("M 0,20 L 200,20");
  animation: distance 3000ms infinite alternate ease-in-out;
  width: 40px;
  height: 40px;
  background: cyan;
  animation-play-state: paused;
}

#example-element.running {
  animation-play-state: running;
}

.wrapper {
  background-image: linear-gradient(
    to bottom,
    transparent,
    transparent 49%,
    black 50%,
    black 51%,
    transparent 52%
  );
  border: 1px solid #cccccc;
  width: 90%;
}

@keyframes distance {
  0% {
    offset-distance: 0%;
  }
  100% {
    offset-distance: 100%;
  }
}

#playback {
  position: absolute;
  top: 0;
  left: 0;
  font-size: 1em;
}
const example = document.getElementById("example-element");
const button = document.getElementById("playback");

button.addEventListener("click", () => {
  if (example.classList.contains("running")) {
    example.classList.remove("running");
    button.textContent = "Play";
  } else {
    example.classList.add("running");
    button.textContent = "Pause";
  }
});

Синтаксис

/* Keyword values */
offset-anchor: top;
offset-anchor: bottom;
offset-anchor: left;
offset-anchor: right;
offset-anchor: center;
offset-anchor: auto;

/* <percentage> values */
offset-anchor: 25% 75%;

/* <length> values */
offset-anchor: 0 0;
offset-anchor: 1cm 2cm;
offset-anchor: 10ch 8em;

/* Edge offsets values */
offset-anchor: bottom 10px right 20px;
offset-anchor: right 3em bottom 10px;

/* Global values */
offset-anchor: inherit;
offset-anchor: initial;
offset-anchor: revert;
offset-anchor: revert-layer;
offset-anchor: unset;

Значения

auto
Для offset-anchor задаётся то же значение, что и для transform-origin элемента, если только offset-path не равен none; в этом случае значение берётся из offset-position.
<position>
position задаёт координату x/y для размещения элемента относительно краёв блока. Её можно определить с помощью от одного до четырёх значений. Подробнее см. справочные страницы о position и background-position. Обратите внимание, что синтаксис позиции из трёх значений не работает ни в одном случае использования <position>, кроме background(-position).

Формальное определение

Начальное значение auto
Применяется к трансформируемым элементам
Наследуется нет
Проценты относительно ширины и высоты опорного блока элемента
Вычисленное значение для <length> — абсолютное значение, в остальных случаях — процент
Тип анимации a <a href="/en-US/docs/Web/CSS/Reference/Values/position_value#interpolation" title="Значения типа данных <position> интерполируются независимо для абсциссы и ординаты. Поскольку скорость определяется одной и той же <easing-function> для обеих координат, точка будет двигаться по прямой.">position</a>

Формальный синтаксис

offset-anchor = 
  auto |
  <position>

<position> = 
  [ [ left | center | right ] || [ top | center | bottom ] | [ left | center | right | <length-percentage> ] [ top | center | bottom | <length-percentage> ]? | [ [ left | right ] <length-percentage> ] && [ [ top | bottom ] <length-percentage> ] ]

<length-percentage> = 
  <length> |
  <percentage>

Примеры

Задание различных значений offset-anchor

В следующем примере три элемента <div> вложены в элементы <section>. Для каждого <div> задан один и тот же offset-path (горизонтальная линия длиной 200 пикселей), анимация перемещает элемент вдоль него. Затем для каждого из трёх элементов задаются разные значения background-color и offset-anchor.

Для каждого <section> задан линейный градиент, образующий горизонтальную линию через его центр. Это позволяет визуально увидеть, где проходят траектории смещения <div>.

Так можно увидеть эффект от разных значений offset-anchor: первое значение, auto, заставляет центральную точку <div> перемещаться по траектории. Два других значения заставляют перемещаться по траектории верхнюю правую и нижнюю левую точки <div> соответственно.

HTML

<section>
  <div class="offset-anchor1"></div>
</section>
<section>
  <div class="offset-anchor2"></div>
</section>
<section>
  <div class="offset-anchor3"></div>
</section>

CSS

div {
  offset-path: path("M 0,20 L 200,20");
  animation: move 3000ms infinite alternate ease-in-out;
  width: 40px;
  height: 40px;
}

section {
  background-image: linear-gradient(
    to bottom,
    transparent,
    transparent 49%,
    black 50%,
    black 51%,
    transparent 52%
  );
  border: 1px solid #cccccc;
  margin-bottom: 10px;
}

.offset-anchor1 {
  offset-anchor: auto;
  background: cyan;
}

.offset-anchor2 {
  offset-anchor: right top;
  background: purple;
}

.offset-anchor3 {
  offset-anchor: left bottom;
  background: magenta;
}

@keyframes move {
  0% {
    offset-distance: 0%;
  }
  100% {
    offset-distance: 100%;
  }
}

Результат

Спецификации

Спецификация
Модуль Motion Path, уровень 1
# свойство offset-anchor

Совместимость с браузерами

Настольные Мобильные
Chrome Edge Firefox Opera Safari Chrome Android Firefox для Android Opera Android Safari на iOS Samsung Internet WebView Android WebView на iOS
offset-anchor
116
116
72
102
16
116
79
78
16
24.0
116
16
auto
116
116
72
102
16
116
79
78
16
24.0
116
16
bottom
116
116
72
102
16
116
79
78
16
24.0
116
16
center
116
116
72
102
16
116
79
78
16
24.0
116
16
left
116
116
72
102
16
116
79
78
16
24.0
116
16
right
116
116
72
102
16
116
79
78
16
24.0
116
16
top
116
116
72
102
16
116
79
78
16
24.0
116
16
x-end
Нет
Нет
Нет
Нет
26
Нет
Нет
Нет
26
Нет
Нет
26
x-start
Нет
Нет
Нет
Нет
26
Нет
Нет
Нет
26
Нет
Нет
26
y-end
Нет
Нет
Нет
Нет
26
Нет
Нет
Нет
26
Нет
Нет
26
y-start
Нет
Нет
Нет
Нет
26
Нет
Нет
Нет
26
Нет
Нет
26

См. также

  • offset
  • offset-distance
  • offset-rotate
  • SVG <path>

© 2005–2025 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/offset-anchor

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API