


The results of the 2024 CSS status survey have been released, and are as fascinating as ever. While each section deserves in-depth analysis, we usually focus most on the parts of the most commonly used CSS features. If you are interested in writing articles about web development (maybe you can start writing with us?), you will particularly want to check out the Reading List section of the feature. It contains the features that survey respondents wish to read after completing the survey, usually consisting of the latest features with less community awareness.
One feature that excites me is my top choice for 2024: CSS anchor positioning, ranked fourth in the survey. You can find the scroll driver animation below, another great feature that has received wide browser support this year. Both are elegant and offer a good developer experience, but combining them opens up new possibilities that most people saw last year fall into the realm of JavaScript.
I want to showcase one of these possibilities while understanding these two features more. Specifically, we will create a blog post where the footnotes pop up as comments next to each paragraph of text.For this demonstration, our requirements are as follows:
- Footnote pops up when it enters the screen.
- Attach them to the corresponding text.
- Footnotes are located on both sides of the screen, so we need a mobile backup solution.
First, we will use the following common blog post layout examples: title, cover image, and body:
The only thing to note is that we occasionally have a paragraph with footnotes:
<code><main><p> 非常有趣的信息! 关于它的脚注 </p> </main></code>Location footnote
In this demonstration, the footnote is located in the body of the article, immediately following the text we want to comment. However, we want them to be attached next to the text as floating bubbles. In the past, we might have to use a combination of absolute and relative positioning and find the correct margin attribute for each footnote.
However, we can now do this using anchor positioning, a feature that allows us to position absolutely positioned elements relative to other elements—not just relative to the container context in which they are located. We'll talk about "anchor" and "target" for a while, so some terms are needed at the beginning:
- Anchor point: This is the element used as a reference to position other elements, hence the name anchor point.
- Target: This is an absolute positioning element positioned relative to one or more anchor points. The goal is the name we use from now on, but in other resources you often find it just "absolutely positioned elements".
Anchors and Targets
It is easy to know that each .footnote
is a target element. However, choosing our anchor points requires more nuance. While it seems that each .note
element should be an anchor element, it is better to choose the entire .post
as the anchor. If we set the position of .footnote
to absolute position, I will explain it:
<code><main><p> 非常有趣的信息! 关于它的脚注 </p> </main></code>
You will notice that the .footnote
elements in the article have been removed from the normal document stream and they are visually hovering over their .note
elements. This is good news! Since they are already aligned on the vertical axis, we just need to use the article as an anchor and move them to the side on the horizontal axis.
At this point, we need to find the correct margin attributes to place them on both sides. Although this is feasible, it is a painful choice because:
- You have to rely on a magic number.
- It depends on the viewport.
- It depends on the content of the footnote as it changes its width.
element is not an anchor by default, so to register an article as an anchor, we must use the anchor-name
property and provide it with a short horizontal identifier (a custom name starting with two short horizontal lines) as the name.
<code>.footnote { position: absolute; }</code>
In this case, our target element will be .footnote
. To use the target element, we can preserve absolute positioning and select the anchor element using the position-anchor
property, which takes the short horizontal line identifier of the anchor. This will make .post
the default anchor point for the target in the next step.
<code>.post { anchor-name: --post; }</code>
Move target
instead of selecting any margin value for the .footnote
or left
attribute of right
, we can use the anchor()
function. It returns a <length></length>
value representing the position on one side of the anchor point, allowing us to always set the target's margin property correctly. So we can connect the left side of the target to the right side of the anchor point and vice versa:
<code>.footnote { position: absolute; position-anchor: --post; }</code>
However, you will notice that it is stuck on one side of the article, with no space in the middle. Fortunately, the margin
attribute works the same way you want to target the target element, and leaves some space between the footnote target and the post anchor. We can also add more styles to make the look more beautiful:
<code>.footnote { position: absolute; position-anchor: --post; /* 将它们放在右侧 */ left: anchor(right); /* 或将它们放在左侧 */ right: anchor(left); /* 每次只使用其中一个! */ }</code>
Finally, all .footnote
elements are on the same side of the article, and if we want to arrange them on each side, we can use the nth-of-type()
selector to select odd and even annotations and set them on opposite sides.
<code>.footnote { /* ... */ background-color: #fff; border-radius: 20px; margin: 0px 20px; padding: 20px; }</code>
We use nth-of-type()
instead of nth-child
because we just want to iterate over the .note
elements instead of all sibling elements.
Remember to remove the last margin statement from .footnote
and then Voice! Our footnotes are located on each side. You'll notice that I also added a small triangle for each footnote, but this is beyond the scope of this article:
View-driven animation
Let's start creating pop-up animations. I found this to be the easiest part because both the view and the scroll-drive animation are as intuitive as possible. We will first register the animation using the common @keyframes
. What we want is to make our footnote start from invisible and then slowly get bigger and visible:
<code><main><p> 非常有趣的信息! 关于它的脚注 </p> </main></code>
This is our animation, now we just need to add it to each .footnote
:
<code>.footnote { position: absolute; }</code>
This itself does nothing. We usually set a animation-duration
for it to start. However, the view-driven animation will not run through the set time, but the animation progress will depend on the position of the element on the screen. To do this, we set animation-timeline
to view()
.
<code>.post { anchor-name: --post; }</code>
This causes the animation to end when the element leaves the screen. We want it to end in a more readable position. The final touch is to set animation-range
to cover 0% cover 40%
. This means, "I want the element to start animation when it is 0% in the view and end when it is 40% in the view."
<code>.footnote { position: absolute; position-anchor: --post; }</code>
Bramus's amazing tool focuses more on scrolling and view-driven animations, which better demonstrates how the animation-range
properties work.
What should I do when I run the mobile terminal?
You may have noticed that this footnote method does not work on smaller screens because there is no space on both sides of the article. The fix is very simple. We want the footnotes to appear as normal footnotes on small screens and as comments on large screens, which we can do by showing our comments only when the screen is larger than a certain threshold (about 1000 pixels). If not, the comments will appear in the body of the article like any other comments you find on the web.
<code>.footnote { position: absolute; position-anchor: --post; /* 将它们放在右侧 */ left: anchor(right); /* 或将它们放在左侧 */ right: anchor(left); /* 每次只使用其中一个! */ }</code>
Now, our comments will only be displayed on both sides if there is enough space:
Summary
If you also like writing content you are passionate about, you will often find yourself going into random tangents, or want to add comments to each paragraph to provide additional context. At least, that's my case, so being able to dynamically display comments is a good addition. Especially when we can do this with just CSS – this is something we couldn’t do a year ago!
The above is the detailed content of Popping Comments With CSS Anchor Positioning and View-Driven Animations. For more information, please follow other related articles on the PHP Chinese website!

Linking CSS files to HTML can be achieved by using elements in part of HTML. 1) Use tags to link local CSS files. 2) Multiple CSS files can be implemented by adding multiple tags. 3) External CSS files use absolute URL links, such as. 4) Ensure the correct use of file paths and CSS file loading order, and optimize performance can use CSS preprocessor to merge files.

Choosing Flexbox or Grid depends on the layout requirements: 1) Flexbox is suitable for one-dimensional layouts, such as navigation bar; 2) Grid is suitable for two-dimensional layouts, such as magazine layouts. The two can be used in the project to improve the layout effect.

The best way to include CSS files is to use tags to introduce external CSS files in the HTML part. 1. Use tags to introduce external CSS files, such as. 2. For small adjustments, inline CSS can be used, but should be used with caution. 3. Large projects can use CSS preprocessors such as Sass or Less to import other CSS files through @import. 4. For performance, CSS files should be merged and CDN should be used, and compressed using tools such as CSSNano.

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

CSSCountersareusedtomanageautomaticnumberinginwebdesigns.1)Theycanbeusedfortablesofcontents,listitems,andcustomnumbering.2)Advancedusesincludenestednumberingsystems.3)Challengesincludebrowsercompatibilityandperformanceissues.4)Creativeusesinvolvecust


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools
