AI 资讯
Undefined CSS variables fail silently: two failures in one evening, and the guard that checks reality
The agent harness I work on has an Electron GUI that shares a renderer with a web shell. Last night it broke twice in one evening. The second break was caused by the first fix. Both were silent. The first one I could explain. The second one was the interesting one, because it exposed something the first fix's test suite could not see — and the fix was a guard that checks reality instead of checking the guard's own arithmetic. Failure one: the light-theme regression. The React shell used CSS custom properties for theming, but a chunk of the migration hardcoded dark-palette hexes directly in component CSS. In light mode the UI looked wrong: dark text on light cards, bad contrast, the exact shape of a half-finished theme refactor. The fix was to route everything through theme variables (the release shipped that as v0.2.84). Straightforward. Failure two: the fix had a hole, and the hole was invisible. After the theme-variable fix landed, a second round of breakage showed up: the task-form background rendered transparent, file-tab hover was dead, badge font sizes and radii were wrong. Nothing threw. No console error, no crash, no failing test. The cause: the fix consumed four variables — --fs-small , --radius-sm , --bg-1 , --bg-hover — that did not exist in tokens.css . A bare var(--x) with no fallback is not an error. At computed-value time the declaration becomes invalid at computed-value time , and the property is treated as if it were never specified. The element just falls back to the default — transparent background, no hover style, default font metrics. The failure mode of an undefined CSS variable is silence. This is the part I want to keep: the bug was not a wrong value. It was a value that was never there, consumed as if it were. The tests passed because the tests asserted behavior, and the behavior was "whatever the browser does with an invalid declaration". The guard that checks definedness. The fix was a guard, not just a value: a static test that walks ever
AI 资讯
Durante meus estudos em ADS, comecei a aprender HTML, CSS e Python. Tenho maior interesse por HTML e CSS, principalmente pela criação de sites e interfaces. Meu principal desafio foi entender como HTML e CSS trabalham juntos e desenvolver a lógica de pro
开源项目
🔥 ConardLi / garden-skills - ConardLi's open-source Skills collection, featuring web desi
GitHub热门项目 | ConardLi's open-source Skills collection, featuring web design, knowledge retrieval, image generation, and more. | Stars: 11,178 | 413 stars today | 语言: CSS
开发者
How to Extract Colors From an Image Using JavaScript and Canvas?
How to Extract Colors From an Image Using JavaScript and Canvas Have you ever looked at an image and wanted to know the exact HEX color of a particular pixel? Designers often need to extract colors from photographs, screenshots, logos, UI designs, and illustrations. You can do this directly in the browser without uploading the image to a server. The browser Canvas API gives us everything we need. Reading pixels with Canvas The basic process is: Load an image. Draw it onto a canvas. Read the pixel data. Convert the RGBA values into a color format such as HEX or RGB. The important API is getImageData() . javascript const imageData = ctx.getImageData(x, y, 1, 1); const pixel = imageData.data; const r = pixel[0]; const g = pixel[1]; const b = pixel[2]; const a = pixel[3];
AI 资讯
Building Fluentic Style: Rethinking How Outside Styles Reach Inside Components
This is part of my Building Fluentic Style series, where I’m writing down the design decisions, tradeoffs, and small surprises from building Fluentic Style . The feeling I keep having is that styling in component frameworks often asks components to fit back into the old HTML + CSS model, instead of asking what CSS composition should look like when components are the main unit. That is not meant as a takedown of CSS. I like CSS. And the HTML + CSS model makes a lot of sense in its own world. In that model, you write HTML, give elements class names, and use selectors when a nested part needs styling. <div class= "card" > <h2 class= "card-title" > Revenue </h2> <p class= "card-body" > $42,300 </p> </div> .card { padding : 16px ; border-radius : 12px ; } .card-title { font-size : 18px ; font-weight : 700 ; } .card .card-body { color : #475569 ; } That model has problems. Global CSS can leak. Naming is hard. Specificity can become painful. Large stylesheets can become difficult to maintain. But the basic mental model is easy to understand: Give the part a name, then style that named part. Even when the ecosystem adds SCSS, BEM, naming conventions, CSS Modules, and other tools, a lot of the core idea stays familiar. There is markup. There are names. There are selectors. Styles reach elements through those names. That world feels coherent because HTML and CSS are built around that relationship. Then components change the shape of UI. Components Change The Unit In React and other component frameworks, we usually stop thinking of UI as one big HTML document. We think in components: < Card title = "Revenue" > $42,300 </ Card > That is a huge improvement. A component owns its internal markup. It receives props. It composes with children. It hides implementation details. It can be typed. It can be transformed by tooling. It can become part of a design system. But styling still has to answer a familiar question: How do I style the thing inside? In HTML + CSS, if I want to style
开源项目
Four things SVG and CSS did that I did not expect
I spent a while building an icon editor that runs entirely in the browser (icons.jamuny.com, free, no account). Here is what cost me the most time. A presentation attribute loses to any author CSS rule I was scaling handle stroke widths by 1 / zoom and writing the result as an attribute. The value was never used. handle . setAttribute ( ' stroke-width ' , String ( 0.35 / zoom )); .handle { stroke-width: 0.35 } in the stylesheet outranks it, because a presentation attribute sits at the very bottom of the cascade. Measured in Chromium: an attribute of 0.05 computed as 0.35px . Every handle thickened on screen as you zoomed in, for months, with no error anywhere. The fix is a custom property, which is an ordinary declaration and wins where an attribute cannot: layer . style . setProperty ( ' --px ' , String ( 1 / zoom )); /* .handle { stroke-width: calc(0.35 * var(--px)) } */ Geometry attributes like r and width are unaffected. They have no CSS counterpart here, so nothing was ever overriding them. A focused SVG element gets a focus ring measured in user units My canvas is 24 units wide and about 620 pixels. Chrome drew its default focus ring at outline-width: 2.72727px in user units, which is about 24 screen pixels. A fat blue disc appeared around every point you clicked. It was reported to me four times, and four times I thinned something of my own that was not the cause. getComputedStyle ( document . activeElement ). outline That one line found it. My rule only covered :focus-visible , which is the keyboard case, and the keyboard case is the one where I draw a ring of my own. var() does work in a presentation attribute, and I wrote down that it doesn't I needed a segment colour that changes with the theme, so the value is oklch(var(--band-l) var(--band-c) 47) . I applied it through a style and put a comment beside it saying var() is not substituted in presentation attributes. It is. Both forms compute to the same colour, including on an element built detached and ap
AI 资讯
A CSS Hover-Reveal Pattern for Technical Specs
The problem on the Gate Seal page The Gate Seal product page for a maritime client needed to present detailed specifications without turning the layout into a wall of text or a table that looked like an export from Excel. The technical detail buyers cared about was present, but visually buried. The requirement was to surface those details in a compact way, keep the implementation CSS-only, and make sure it still worked with keyboard navigation. The hover-reveal pattern The pattern below uses a hover-reveal on key specification rows. On desktop, moving the cursor over a spec row reveals additional context. With a keyboard, focusing the same row does the same thing. No JavaScript is required for the basic interaction. Structurally, each spec item is a container with two layers of content: Always-visible summary (label and primary value) Hidden detail that appears on hover or focus Here is a simplified version of the markup: <div class="spec-list"> <button class="spec-item"> <div class="spec-main"> <span class="spec-label">Gate size</span> <span class="spec-value">Up to 6 m</span> </div> <div class="spec-detail"> Custom diameters available for retrofit situations. </div> </button> <button class="spec-item"> <div class="spec-main"> <span class="spec-label">Seal material</span> <span class="spec-value">EPDM / NBR</span> </div> <div class="spec-detail"> Oil-resistant compounds for lock gates in heavy traffic.</div> </button> </div> The choice of <button> here is deliberate: it is naturally focusable, works with keyboard navigation, and is announced as an interactive element by assistive technology. In a production implementation, the button semantics can be adapted depending on whether you need a true button or a different element with role="button" . The CSS-only interaction The interaction is controlled through :hover and :focus-visible , with a basic transition for a smoother reveal. .spec-list { display: grid; gap: 0.75rem; } .spec-item { width: 100%; text-align: left
AI 资讯
How I Built a Color Picker That Actually Converts Colors Correctly (HEX/RGB/HSL)
While working on a design system recently, I kept running into the same frustrating problem: I'd grab a color from Figma in HEX format, need it in HSL for a CSS variable, and end up bouncing between three different websites just to convert one value. Each site had its own UI quirks, some required JavaScript to be enabled, and none of them gave me a proper color scheme alongside the conversion. So I did what any reasonable developer would do — I built my own. Because apparently I enjoy reinventing wheels. The Problem With Existing Solutions The existing color converter tools online weren't bad, but they had a few issues that bugged me: They were slow — many loaded heavy JavaScript libraries just to do simple math They lacked context — I wanted to see complementary colors and schemes alongside the conversion They were ad-heavy — I don't want to dodge pop-ups while trying to match a shade of blue I wanted something that felt like a native tool: instant, offline-capable, and comprehensive. A single HTML file that I could open, use, and close without ceremony. The Architecture Decision The first decision was whether to use a library or write the conversion logic myself. Libraries like color (npm) are battle-tested, but they add weight. Since this is a browser-only tool with no build step, I decided to write the conversions in vanilla JavaScript. Here's the core conversion logic that handles the heavy lifting: function hslToRgb ( h , s , l ) { s /= 100 ; l /= 100 ; const k = n => ( n + h / 30 ) % 12 ; const a = s * Math . min ( l , 1 - l ); const f = n => l - a * Math . max ( - 1 , Math . min ( k ( n ) - 3 , Math . min ( 9 - k ( n ), 1 ))); return [ Math . round ( f ( 0 ) * 255 ), Math . round ( f ( 8 ) * 255 ), Math . round ( f ( 4 ) * 255 )]; } This is the most concise HSL-to-RGB conversion I know. It's a compact version of the standard formula that avoids the typical case-based approach. The math checks out for all edge cases, including grayscale (when s = 0 ). AI-Assi
开发者
CSS Navigation Matching, Early Days
Apply a style when someone navigates from one specific page to another. The idea being it'd make the sources for cross-document view transitions declarative in CSS rather than managing that stuff in JavaScript. CSS Navigation Matching, Early Days originally handwritten and published with love on CSS-Tricks . You should really get the newsletter as well.
开发者
Stop Writing Media Queries for Font Size
A teammate opened a PR titled "fix hero heading on small screens." The diff added a media query. Mine, reviewing it, found four more already in that file — one per breakpoint, added over eighteen months by four different people, each one patching the width the last person didn't think of: .hero-heading { font-size : 3rem ; } @media ( max-width : 1200px ) { .hero-heading { font-size : 2.5rem ; } } @media ( max-width : 992px ) { .hero-heading { font-size : 2.25rem ; } } @media ( max-width : 768px ) { .hero-heading { font-size : 1.75rem ; } } @media ( max-width : 480px ) { .hero-heading { font-size : 1.5rem ; } } Five rules to make one number — the font size of one heading — track the width of the screen it's on. And it still didn't work everywhere: resize the window to 850px and the heading is stuck at the 992px value, a little too big for the space it actually has. Every gap between breakpoints is a size nobody chose, it's just whatever the nearest rule left behind. Here's the part that stings: none of this has been necessary since 2020. The fix that isn't a breakpoint at all clamp() takes three values — a minimum, a preferred value, and a maximum — and returns whichever one the situation calls for: .hero-heading { font-size : clamp ( 1.5rem , 1rem + 2vw , 3rem ); } Read it as a sentence: never smaller than 1.5rem, never bigger than 3rem, and in between, scale with the viewport. The five media queries above collapse into that one line — and unlike them, it doesn't have gaps. clamp() recalculates the size continuously, every pixel the viewport moves, so there's no "850px value" that got left behind. It's a formula, not a lookup table. The middle value is where the "preferred" size lives, and it's 1rem + 2vw — a fixed part plus a viewport-relative part — not just 4vw on its own. That's not decoration. It's the one part of this pattern worth getting right, because the shortcut version quietly breaks something. The version that looks fine and isn't The formula you'll see
AI 资讯
I Ripped Out a Carousel Library. CSS Replaced It.
The bug ticket said "carousel feels broken on trackpad." It took me forty minutes to find the actual...
AI 资讯
Soft Boil — six minutes, and you cannot get it wrong
This is a submission for Frontend Challenge - Comfort Food Edition, CSS Art . Inspiration My other two entries were about a moment and a ritual. This one is about the opposite: the dish you fall back on when you have no skill, no energy and no plan. Boiled eggs are what you make when you cannot cook. Six minutes, one pan,and the comfort is precisely that it is not possible to get it wrong . Two choices made it worth drawing rather than just worth eating. A glass bowl, so you can see the boil. In a steel pan the interesting half of this is hidden. Glass also turned out to be the exact opposite problem to the terracotta in my chai piece — unglazed clay is matte and forgives a sloppy gradient, glass shows you every single one. An induction hob, for the light. I finished the fridge piece saying the one piece of advice I'd give is pick a scene with a light source in it . So I did it again on purpose. The element ring is the only warm thing in an otherwise cold grey kitchen, and it lights the water from underneath. Everything here is a div , a gradient or a shadow. No SVG, no images, no canvas. Demo Press Turn off the heat and give it a few seconds. The ring dies back, the bubbles thin out, and the eggs slowly stop moving — then put it back on and watch the pan come to the boil in stages. That build-up is the part I'd most like you to see, and it's the whole subject of this post. Journey Nothing in this picture is transparent The obvious way to draw a glass bowl is backdrop-filter . I'd advise against building a picture on it — support is uneven enough that the piece falls apart somewhere, and it's expensive. So the transparency is painted. The water is drawn first as its own element, and then a front wall of highlights sits over the top of it: two vertical speculars down the sides for the curve of the glass, a soft wash across the middle for the thickness of the pane, and a rolled lip at the top, which is the one place glass is genuinely opaque enough to draw as a solid.
AI 资讯
CSS Masala Dosa — A Plate of Comfort 🍽️
This is a submission for Frontend Challenge - Comfort Food Edition, CSS Art . Inspiration For my CSS Art submission, I wanted to create something that represents comfort food from South India — Masala Dosa . 🇮🇳 A crispy, golden dosa served with potato masala, coconut chutney, tomato chutney, and a warm bowl of sambar is more than just a meal. It's one of those dishes that immediately feels familiar and comforting. I decided to recreate the entire plate using HTML and CSS , without using food images or external graphics. The goal was to turn a simple plate of masala dosa into a small CSS illustration while keeping the focus on CSS techniques such as: CSS gradients Radial and repeating gradients Border-radius based shapes Box shadows Pseudo-elements CSS animations Responsive layouts Layering and positioning The project is called "CSS Masala Dosa — A Plate of Comfort" . Demo 🍽️ Live CodePen Project: CSS Masala Dosa — A Plate of Comfort View the CSS Masala Dosa project on CodePen Journey I started with the idea of creating a single plate entirely from CSS . Instead of using an image for the dosa, I built the main shape using layered gradients and rounded shapes. The different colors and textures help create the crispy, golden appearance of the dosa. Then I added the individual elements of the meal: 🥞 Masala Dosa — built using multiple gradients, shadows, and layered shapes. 🥔 Potato Masala — represented using small CSS shapes for potato pieces, onions, and curry leaves. 🥥 Coconut Chutney — created using a circular CSS shape with subtle texture details. 🌶️ Tomato Chutney — another CSS-only circular element with layered gradients. 🥣 Sambar — built as a small bowl using nested circular elements and gradients. 🌿 Banana Leaf — created with gradients, shadows, and a CSS vein to give it a natural appearance. ♨️ Steam — animated using CSS @keyframes to give the dosa a freshly-served feeling. One of the things I particularly enjoyed was creating the food textures without images
AI 资讯
CSS Gradients in One Screen: linear, radial, conic, and the rules nobody spells out
If you've only ever shipped linear-gradient(to right, blue, red) , you're using about one-third of what CSS gradients can do. There are only three functions, and the mental model for each is small. Here's the whole thing in one read. The one fact that makes everything click A gradient is not an image file. Per MDN , a <gradient> is a special kind of <image> that the browser generates at render time . So it: scales to any size without blurring (it's drawn, not sampled) weighs zero bytes (no file, no HTTP request) edits with one hex value instead of a re-export That's why gradients exist. Everything below is just how to steer them. Three functions, three shapes Function Shape Reach for it when linear-gradient() straight line along an axis backgrounds, buttons, overlays radial-gradient() outward from a center point spotlights, glows, vignettes conic-gradient() rotational sweep around a center pie charts, color wheels, spinners Linear - the workhorse background : linear-gradient ( to right , #ff7e5f , #feb47b ); /* orange→peach */ background : linear-gradient ( 135 deg , #6366 f1 0 %, #ec4899 100 %); /* indigo→pink */ Direction is an angle ( 45deg ) or a keyword ( to right , to top right ). Stops are a color plus an optional position. Radial - when the fade should read as light background : radial-gradient ( circle , #fff , #000 ); Shape ( circle vs ellipse ), center position, and sizing keywords ( closest-side , farthest-corner ) do the work. Because the fade tracks distance from a point, radial reads as depth - perfect for glows, vignettes, and spotlight effects. Conic - the one most people skip background : conic-gradient ( #f00 0 25 %, #0 f0 25 % 50 %, #00 f 50 % 75 %, #ff0 75 %); Conic sweeps by angle , not distance. That single difference makes it the right tool for pie charts and color wheels - effects that were hacky before conic-gradient() shipped. The rule that surprises everyone Two color stops at the same position don't fade - they make a hard edge: backgrou
AI 资讯
جعلنا موقعنا غير قابل للضغط مرتين، ولم يكن الخطأ في الكود
مرتين خلال أسابيع صار موقعنا يبدو سليمًا تمامًا ولا يستجيب للضغط. الصفحة تُحمَّل، والتصميم في مكانه، والكونسول نظيف، والزوار لا يستطيعون فتح أي رابط. في المرتين لم يكن السبب خطأً برمجيًا بالمعنى المعتاد. كان سلوكًا موثّقًا في المتصفح يعمل كما صُمّم تمامًا، لكنه انطبق على نطاق أوسع مما توقّعنا. والأخطر أن اختباراتنا الآلية مرّت بنجاح في الحالتين. الحادثة الأولى: إعداد واحد عطّل سبعين عنصرًا أضفنا ويدجت مساعد ذكي للموقع، وفيه إعداد يفتح نافذة المحادثة تلقائيًا عند دخول الزائر. فعّلناه. بعدها صارت الصفحة ميتة. الروابط لا تُفتح، والأزرار لا تستجيب، وحقول البحث لا تستقبل كتابة. السبب أن الويدجت يعتمد نمطًا شائعًا في نوافذ الحوار: عند فتح النافذة، يضع السمة inert على كل ما عداها حتى لا يتشتت التركيز ولا يهرب مؤشر لوحة المفاتيح خارجها. سلوك صحيح ومطلوب في الحوارات. المشكلة أن الفتح التلقائي يجعل هذه الحالة هي حالة الصفحة الافتراضية عند كل زيارة . سبعون عنصرًا في الصفحة ورثوا inert ، وبقوا كذلك حتى يغلق الزائر نافذة لم يطلب فتحها أصلًا. // ما يفعله الويدجت عند الفتح document . querySelectorAll ( ' body > *:not(.assistant-root) ' ) . forEach (( el ) => el . setAttribute ( ' inert ' , '' )); و inert ليست سمة تجميلية. الفحص السريع يوضح مداها: const el = document . querySelector ( ' a.main-cta ' ); el . offsetParent !== null ; // true — العنصر مرئي getComputedStyle ( el ). pointerEvents ; // 'auto' — لا شيء يمنع المؤشر el . getBoundingClientRect (). width ; // 180 — له مساحة حقيقية el . matches ( ' :disabled ' ); // false — ليس معطّلًا el . closest ( ' [inert] ' ) !== null ; // true ← هنا الجواب كل فحص اعتدنا عليه يقول إن العنصر سليم. inert تعمل في طبقة أخرى: تُخرج العنصر وكل أبنائه من شجرة الوصول، وتلغي استقباله لأحداث المؤشر والتركيز، بلا أي أثر في الأنماط المحسوبة . لماذا مرّت الاختبارات اختباراتنا كانت تسأل الأسئلة المعتادة: هل العنصر موجود في الـDOM؟ هل هو مرئي؟ هل نصّه صحيح؟ الإجابات كلها نعم. ما كشف العطل كان لقطة شاشة نظر إليها إنسان ، ثم محاولة ضغط واحدة. الفحوص البرمجية كانت تصف صفحة سليمة بينما الزائر يرى صفحة جامدة. إن كنت تستخدم أي مكوّن يطبّق inert ، أضف هذا التأك
AI 资讯
La Abuela — Comfort Food from Madrid
La Abuela — Comfort Food from Madrid 🍲 A cozy, fully accessible landing page for an imaginary family restaurant in Madrid, built from scratch with vanilla HTML, CSS and JavaScript for the DEV Frontend Challenge: Comfort Food Edition. 🔗 Live demo: https://laabuela.bmops.tech 💻 Interactive pen (CodePen): The story La Abuela ("the grandmother") is a tiny four-table restaurant in Lavapiés, Madrid. In 1987, Abuela Carmen opened it with one rule: if it wouldn't be served at her Sunday table, it wouldn't be served here. Forty years later, the menu still has three dishes — caldo, croquetas, lentejas — and the pot still simmers for three hours. The page tells that story through a warm terracotta-and-cream palette and five illustrations drawn entirely in pure CSS — no images, no SVG, no canvas. What I built Hero — a clay pot in pure CSS: gradient body with layered inset shadows for volume, decorative band, handles, a two-tongued fire with a glowing core, a wooden table with grain, a light sweep across the heading, and animated organic steam Our story — a bowl of caldo with a wooden spoon and a terracotta heart, all divs and box-shadows The menu — three dish cards, each with its own pure-CSS illustration: a steaming bowl of caldo, three golden croquetas with crispy texture and a pool of salsa, and a dark bowl of lentils with nine individual grains The recipe — an accessible accordion unlocking Abuela's caldo, step by step Quotes — from regulars (including one from Osaka who cried into the caldo) Booking form — with inline validation, clear labels and a friendly confirmation Footer — hours, address, and a wink to Carmen The art is pure CSS — no images, no SVG Every illustration is built the way : nested absolutely-positioned divs, layered box-shadow (inset shadows give the clay its volume and the croquettes their crust), organic border-radius , and radial gradients for light. The pot alone uses four shadow layers to feel round instead of flat. The steam is animated with pure CS
开发者
Creating modern forms with form.fscss — pure CSS
Floating labels. Inline validation. Custom checkboxes, radios, and a toggle switch. A gradient button with a press-down micro-interaction. Every bit of it below is CSS — no form library, no useState , no event listener wiring up a class toggle. That's form.fscss — the module in the FSCSS ecosystem. Same philosophy each time: solve the hard visual problem once, ship it as importable mixins, let the browser do the actual work. <script src= "https://cdn.jsdelivr.net/npm/fscss@1.1.24/exec.min.js" defer ></script> <style> @import (( * ) from form ) @ form-root () @ form-group (. form-group ) @ form-input (. form-input ) @ form-label (. form-label ) @ form-float (. form-group , . form-input , . form-label ) @ form-checkbox (. form-checkbox ) @ form-btn (. form-btn ) @ form-btn-primary (. form-btn-primary ) </style> <div class= "form-group" > <input class= "form-input" type= "text" placeholder= " " > <label class= "form-label" > Full name </label> </div> <label class= "form-checkbox" > <input type= "checkbox" checked ><span></span> I agree to the Terms </label> <button class= "form-btn form-btn-primary" > Create account </button> The two tricks doing all the work Forms feel like they need JavaScript because most tutorials reach for it immediately. Two native CSS mechanisms cover almost everything a "modern" form needs. Floating labels run entirely on :placeholder-shown . Give the input placeholder=" " — a literal space, not empty — and the browser now knows, purely in CSS, whether the field is empty and unfocused: .form-input :focus + .form-label , .form-input :not ( :placeholder-shown ) + .form-label { top : -9px ; font-size : 11px ; color : var ( --form-accent ); } No state, no class toggling on keyup. The label just reacts to what the browser already knows about the input. Checkboxes, radios, and the switch all use the classic checkbox-hack: the real <input> stays in the DOM (so it keeps native keyboard support and form submission) but is visually hidden, and a sibling
开发者
CSS Anchor Positioning: Building Tooltips Without JavaScript Positioning Hacks
Introduction Positioning a tooltip sounds simple. Put a small box next to a button. Done. But anyone who has built one knows that it can quickly turn into: position: absolute calculating coordinates listening for resize events handling scrolling checking whether the tooltip fits on screen and sometimes pulling in an entire positioning library Modern CSS is starting to change that. CSS Anchor Positioning lets us position one element relative to another directly in CSS. Let's look at what that means with a very simple tooltip. What Is CSS Anchor Positioning? CSS Anchor Positioning allows one element to act as an anchor and another element to position itself relative to that anchor. Think about UI components such as: Tooltips Dropdown menus Popovers Context menus Floating labels These elements usually need to appear next to another element. Instead of calculating where they belong with JavaScript, we can now describe that relationship in CSS. Conceptually, we're saying: "This button is my anchor. Position this tooltip relative to it." A Simple Example Imagine we have a button: <button class= "info-button" > More info </button> <div class= "tooltip" > Your changes are saved automatically. </div> We want the tooltip to appear directly below the button. First, let's make the button an anchor. .info-button { anchor-name : --info-button ; } We've now given the button an anchor name. Next, connect our tooltip to it. .tooltip { position : absolute ; position-anchor : --info-button ; top : anchor ( bottom ); left : anchor ( left ); margin-top : 8px ; } That's the interesting part. top : anchor ( bottom ); tells the browser: Position the top of the tooltip at the bottom of the anchor. And: left : anchor ( left ); aligns its left side with the button. No getBoundingClientRect() . No coordinate calculations. No resize listener just to figure out where the tooltip belongs. Why Is This Useful? Before Anchor Positioning, we often had to manage positioning ourselves. A simplified Jav
开发者
Morning on a Banana Leaf: A South Indian Breakfast Still Life in CSS
This is a submission for Frontend Challenge - Comfort Food Edition, CSS Art. ...
开发者
The Pot - a borscht in pure CSS
This is a submission for Frontend Challenge - Comfort Food Edition, CSS Art. ...