26, జనవరి 2025, ఆదివారం

Positioning Text Around Elements With CSS Offset

 When it comes to positioning elements on a page, including text, there are many ways to go about it in CSS — the literal position property with corresponding inset-* properties, translate, margin, anchor() (limited browser support at the moment), and so forth. The offset property is another one that belongs in that list.

The offset property is typically used for animating an element along a predetermined path. For instance, the square in the following example traverses a circular path:

A registered CSS custom property (--p) is used to set and animate the offset distance of the square element. The animation is possible because an element can be positioned at any point in a given path using offset. and maybe you didn’t know this, but offset is a shorthand property comprised of the following constituent properties:

  • offset-position: The path’s starting point
  • offset-path: The shape along which the element can be moved
  • offset-distance: A distance along the path on which the element is moved
  • offset-rotate: The rotation angle of an element relative to its anchor point and offset path
  • offset-anchor: A position within the element that’s aligned to the path

The offset-path property is the one that’s important to what we’re trying to achieve. It accepts a shape value — including SVG shapes or CSS shape functions — as well as reference boxes of the containing element to create the path.

Reference boxes? Those are an element’s dimensions according to the CSS Box Model, including content-boxpadding-boxborder-box, as well as SVG contexts, such as the view-boxfill-box, and stroke-boxThese simplify how we position elements along the edges of their containing elements. Here’s an example: all the small squares below are placed in the default top-left corner of their containing elements’ content-box. In contrast, the small circles are positioned along the top-right corner (25% into their containing elements’ square perimeter) of the content-boxborder-box, and padding-box, respectively.

<div class="circle">
  <div class="square"></div>
</div>
@property --p {
  syntax: '<percentage>';
  inherits: false;
  initial-value: 0%;
}
.square {
  offset: top 50% right 50% circle(50%) var(--p);
  transition: --p 1s linear;

  /* Equivalent to:
    offset-position: top 50% right 50%;
    offset-path: circle(50%);
    offset-distance: var(--p); */

  /* etc. */
}

.circle:hover .square{ --p: 100%; }

కామెంట్‌లు లేవు:

కామెంట్‌ను పోస్ట్ చేయండి