Tag: Many

Which SVG technique performs best for way too many icons?

Tyler Sticka digs in here in the best possible way: by making a test page and literally measuring performance. Maybe 1,000 icons is a little bit of an edge case, but hey, 250 rows of data with four icons in each gets you there. Tyler covers the nuances carefully in the post. The different techniques tested: inline <svg>, same-document sprite <symbol>s, external-document sprite <symbol>s, <img> with an external source, <img> with a data URL, <img> with a filter, <div> with a background-image of an external source, <div> with a background-image of a data URL, and a <div> with a mask. Phew! That’s a lot — and they are all useful techniques in their own right.

Which technique won? Inline <svg>, unless the SVGs are rather complex, then <img> is better. That’s what I would have put my money on. I’ve been on that train for a while now.

To Shared LinkPermalink on CSS-Tricks


The post Which SVG technique performs best for way too many icons? appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

, , , ,

The Many Faces of VS Code in the Browser

VS Code is built from web technologies (HTML, CSS, and JavaScript), but dare I say today it’s mostly used a local app that’s installed on your machine. That’s starting to shift, though, as there has been an absolute explosion of places VS Code is becoming available to use on the web. I’d say it’s kind of a big deal, as VS Code isn’t just some editor; it’s the predominant editor used by web developers. Availability on the web means being able to use it without installing software, which is significant for places, like schools, where managing all that is a pain, and computers, like Chromebooks, where you don’t really install local software at all.

It’s actually kind of confusing all the different places this shows up, so let’s look at the landscape as I see it today.

vscode.dev

It was just a few weeks ago as I write that Microsoft dropped vscode.dev. Chris Dias:

Modern browsers that support the File System Access API (Edge and Chrome today) allow web pages to access the local file system (with your permission). This simple gateway to the local machine quickly opens some interesting scenarios for using VS Code for the Web as a zero-installation local development tool

It’s just Edge and Chrome that have this API right now, but even if you can’t get it, you can still upload files, or perhaps more usefully, open a repo. If it does work, it’s basically… VS Code in the browser. It can open your local folders and it behaves largely just like your local VS Code app does.

I haven’t worked a full day in it or anything, but basic usage seems about the same. There is some very explicit permission-granting you have to do, and keyboard commands are a bit weird as you’re having to fight the browsers keyboard commands. Plus, there is no working terminal.

Other than that it feels about the same. Even stuff like “Find in Project” seems just as fast as local, even on large sites.

GitHub.dev: The whole “Press Period (.) on any GitHub Repo” Thing

You also get VS Code in the browser if you go to github.dev, but it’s not quite wired up the same.

You don’t have the opportunity here to open a local folder. Instead, you can quickly look at a GitHub repo.

But perhaps even more notably, you can make changes, save the files, then use the Source Control panel right there to commit the code or make a pull request.

You’d think vscode.dev and github.dev would merge into one at some point, but who knows.

Oh and hey, thinking of this in reverse, you can open GitHub repos on your locally installed VS Code as well directly (even without cloning it).

There is no terminal or preview in those first two, but there is with GitHub Codespaces.

GitHub Codespaces is also VS Code in the browser, but fancier. For one thing, you’re auth’d into Microsoft-land while using it, meaning it’s running all your VS Code extensions that you run locally. But perhaps a bigger deal is that you get a working terminal. When you spin it up, you see:

Welcome to Codespaces! You are on our default image.

• It includes runtimes and tools for Python, Node.js, Docker, and more. See the full list here: https://aka.ms/ghcs-default-image
• Want to use a custom image instead? Learn more here: https://aka.ms/configure-codespace

🔍 To explore VS Code to its fullest, search using the Command Palette (Cmd/Ctrl + Shift + P or F1).

📝 Edit away, run your app as usual, and we’ll automatically make it available for you to access.

On a typical npm-powered project, you can npm run you scripts and you’ll get a URL running the project as a preview.

This is in the same territory as Gitpod.

Gitpod is a lot like GitHub CodeSpaces in that it’s VS Code in the browser but with a working terminal. That terminal is like a full-on Docker/Linux environment, so you’ve got a lot of power there. It might even be able to mimic your production environment, assuming you’re using all things that Gitpod supports.

It’s also worth noting that Gitpod jacks in “workspaces” that run services. On that demo project above, a MongoDB instance is running on one port, and a preview server is open on another port, which you can see in a mock browser interface there. Being able to preview the project you’re working on is an absolute must and they are handling that elegantly.

Perhaps you’ll remember we used Gitpod in a video we did about DataStax Astra (jumplink) which worked out very nicely.

My (absolute) guess is that Gitpod could be acquired by Microsoft. It seems like Microsoft is headed in this exact direction and getting bought is certainly better than getting steamrolled by the company that makes the core tech that you’re using. You gotta play the “no—this is good! it validates the market! we baked you an awkward cake!” for a while but I can’t imagine it ends well.

This is also a lot like CodeSandbox or Stackblitz.

Straight up, CodeSandbox and Stackblitz also run VS Code in the browser. Or… something that leverages bits and bobs of VS Code at least (a recent episode of Syntax gets into the StackBlitz approach a bit).

You can also install VS Code on your own server.

That’s what Coder’s code-server ia. So, rather than use someone else’s web version of VS Code, you use your own.

You could run VS Code on a local server, but I imagine the big play here is that you run it on live cloud web servers you control. Maybe servers, you know, with your code running on them, so you can use this to literally edit the files on the server. Who needs VIM when you have full-blown VS Code (lolz).

We talked about the school use case, and I imagine this is compelling for that as well, since the school might not even rely on a third-party service, but host it themselves. The iPad/Chromebook use cases are relevant here, too, and perhaps even more so. The docs say “Preserve battery life when you’re on the go; all intensive tasks run on your server,” which I guess means that unlike vscode.dev where tasks like “Find in Project” are (presumably) done on your local machine, they are done by the server (maybe slower, but not slower than a $ 200 laptop?).


There is clearly something in the water with all this. I’m bullish on web-based IDEs. Just look at what’s happening with Figma (kicking ass), which I would argue is one-third due to the product meetings screen designers need with little bloat, one-third due to the simple team and permissions model, and one-third due to the fact that it’s built web-first.


The post The Many Faces of VS Code in the Browser appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

, , ,
[Top]

So many little design helper sites!

I had one of those little single-serving designer helper sites bookmarked the other day: getwaves.io. Randomized SVG waves! Lots of cool options! Easy to customize! Easy to copy and paste! Well played, z creative labs.

But then I saw the little link at the top of the page, that it was part of something called Haikei. So I checked that out, and holy mackerel, it’s great! There are a dozen or more similar “generators” within one app, each just as well done as the SVG waves one.

Random scattering of vector stars.

Kind of reminds me of Omatsuri which is a similar collection of useful little on-off tools.

But heck, those are just two apps, even if they are collections of mini apps in an of themselves. Around the same time, I became aware of tiny-helpers.dev, which is a roundup site of all sorts of these little one-off helper sites. Haikei and Omatsuri are both on there, along with many hundred more. Just the SVG area alone is super:

I’m sure y’all find these things just as useful as I do. They don’t make us lazy, they make us efficient. I know how to make a pattern. I know how to draw a curve with a Pen Tool. I know how to convert SVG into JSX. But using a dedicated tool makes me faster and better at it. And sometimes I don’t know how to do those things, but that doesn’t mean I can’t take advantage. Fake it ’til you make it, right?


The post So many little design helper sites! appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

, , , ,
[Top]

So many little design helper sites!

I had one of those little single-serving designer helper sites bookmarked the other day: getwaves.io. Randomized SVG waves! Lots of cool options! Easy to customize! Easy to copy and paste! Well played, z creative labs.

But then I saw the little link at the top of the page, that it was part of something called Haikei. So I checked that out, and holy mackerel, it’s great! There are a dozen or more similar “generators” within one app, each just as well done as the SVG waves one.

Random scattering of vector stars.

Kind of reminds me of Omatsuri which is a similar collection of useful little on-off tools.

But heck, those are just two apps, even if they are collections of mini apps in an of themselves. Around the same time, I became aware of tiny-helpers.dev, which is a roundup site of all sorts of these little one-off helper sites. Haikei and Omatsuri are both on there, along with many hundred more. Just the SVG area alone is super:

I’m sure y’all find these things just as useful as I do. They don’t make us lazy, they make us efficient. I know how to make a pattern. I know how to draw a curve with a Pen Tool. I know how to convert SVG into JSX. But using a dedicated tool makes me faster and better at it. And sometimes I don’t know how to do those things, but that doesn’t mean I can’t take advantage. Fake it ’til you make it, right?


The post So many little design helper sites! appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

, , , ,
[Top]

Too Many SVGs Clogging Up Your Markup? Try `use`.

Recently, I had to make a web page displaying a bunch of SVG graphs for an analytics dashboard. I used a bunch of <rect>, <line> and <text> elements on each graph to visualize certain metrics.

This works and renders just fine, but results in a bloated DOM tree, where each shape is represented as separate nodes. Displaying all 50 graphs simultaneously on a web page results in 5,951 DOM elements in total, which is far too many.

We might display 50-60 different graphs at a time, all with complex DOM trees.

This is not optimal for several reasons:

  • A large DOM increases memory usage, longer style calculations, and costly layout reflows.
  • It will increases the size of the file on the client side.
  • Lighthouse penalizes the performance and SEO scores.
  • Maintainability is a nightmare — even if we use a templating system — because there’s still a lot of cruft and repetition.
  • It doesn’t scale. Adding more graphs only exacerbates these issues.

If we take a closer look at the graphs, we can see a lot of repeated elements.

Each graph ends up sharing lots of repeated elements with the rest.

Here’s dummy markup that’s similar to the graphs we’re using:

<svg   xmlns="http://www.w3.org/2000/svg"   version="1.1"   width="500"   height="200"   viewBox="0 0 500 200" >   <!--     📊 Render our graph bars as boxes to visualise our data.     This part is different for each graph, since each of them displays different sets of data.   -->   <g class="graph-data">     <rect x="10" y="20" width="10" height="80" fill="#e74c3c" />     <rect x="30" y="20" width="10" height="30" fill="#16a085" />     <rect x="50" y="20" width="10" height="44" fill="#16a085" />     <rect x="70" y="20" width="10" height="110" fill="#e74c3c" />     <!-- Render the rest of the graph boxes ... -->   </g>    <!--     Render our graph footer lines and labels.   -->   <g class="graph-footer">     <!-- Left side labels -->     <text x="10" y="40" fill="white">400k</text>     <text x="10" y="60" fill="white">300k</text>     <text x="10" y="80" fill="white">200k</text>     <!-- Footer labels -->     <text x="10" y="190" fill="white">01</text>     <text x="30" y="190" fill="white">11</text>     <text x="50" y="190" fill="white">21</text>     <!-- Footer lines -->     <line x1="2" y1="195" x2="2" y2="200" stroke="white" strokeWidth="1" />     <line x1="4" y1="195" x2="2" y2="200" stroke="white" strokeWidth="1" />     <line x1="6" y1="195" x2="2" y2="200" stroke="white" strokeWidth="1" />     <line x1="8" y1="195" x2="2" y2="200" stroke="white" strokeWidth="1" />     <!-- Rest of the footer lines... -->   </g> </svg>

And here is a live demo. While the page renders fine the graph’s footer markup is constantly redeclared and all of the DOM nodes are duplicated.

The solution? The SVG element.

Luckily for us, SVG has a <use> tag that lets us declare something like our graph footer just once and then simply reference it from anywhere on the page to render it as many times as we want. From MDN:

The <use> element takes nodes from within the SVG document, and duplicates them somewhere else. The effect is the same as if the nodes were deeply cloned into a non-exposed DOM, then pasted where the use element is.

That’s exactly what we want! In a sense, <use> is like a modular component, allowing us to drop instances of the same element anywhere we’d like. But instead of props and such to populate the content, we reference which part of the SVG file we want to display. For those of you familiar with graphics programming APIs, such as WebGL, a good analogy would be Geometry Instancing. We declare the thing we want to draw once and then can keep reusing it as a reference, while being able to change the position, scale, rotation and colors of each instance.

Instead of drawing the footer lines and labels of our graph individually for each graph instance then redeclaring it over and over with new markup, we can render the graph once in a separate SVG and simply start referencing it when needed. The <use> tag allows us to reference elements from other inline SVG elements just fine.

Let’s put it to use

We’re going to move the SVG group for the graph footer — <g class="graph-footer"> — to a separate <svg> element on the page. It won’t be visible on the front end. Instead, this <svg> will be hidden with display: none and only contain a bunch of <defs>.

And what exactly is the <defs> element? MDN to the rescue once again:

The <defs> element is used to store graphical objects that will be used at a later time. Objects created inside a <defs> element are not rendered directly. To display them you have to reference them (with a <use> element for example).

Armed with that information, here’s the updated SVG code. We’re going to drop it right at the top of the page. If you’re templating, this would go in some sort of global template, like a header, so it’s included everywhere.

<!--   ⚠️ Notice how we visually hide the SVG containing the reference graphic with display: none;   This is to prevent it from occupying empty space on our page. The graphic will work just fine and we will be able to reference it from elsewhere on our page --> <svg   xmlns="http://www.w3.org/2000/svg"   version="1.1"   width="500"   height="200"   viewBox="0 0 500 200"   style="display: none;" >   <!--     By wrapping our reference graphic in a <defs> tag we will make sure it does not get rendered here, only when it's referenced -->   <defs>     <g id="graph-footer">       <!-- Left side labels -->       <text x="10" y="40" fill="white">400k</text>       <text x="10" y="60" fill="white">300k</text>       <text x="10" y="80" fill="white">200k</text>       <!-- Footer labels -->       <text x="10" y="190" fill="white">01</text>       <text x="30" y="190" fill="white">11</text>       <text x="50" y="190" fill="white">21</text>       <!-- Footer lines -->       <line x1="2" y1="195" x2="2" y2="200" stroke="white" strokeWidth="1" />       <line x1="4" y1="195" x2="2" y2="200" stroke="white" strokeWidth="1" />       <line x1="6" y1="195" x2="2" y2="200" stroke="white" strokeWidth="1" />       <line x1="8" y1="195" x2="2" y2="200" stroke="white" strokeWidth="1" />       <!-- Rest of the footer lines... -->     </g>   </defs> </svg>

Notice that we gave our group an ID of graph-footer. This is important, as it is the hook for when we reach for <use>.

So, what we do is drop another <svg> on the page that includes the graph data it needs, but then reference #graph-footer in <use> to render the footer of the graph. This way, there’s no need to redeclaring the code for the footer for every single graph.

Look how how much cleaner the code for a graph instance is when <use> is in.. umm, use.

<svg   xmlns="http://www.w3.org/2000/svg"   version="1.1"   width="500"   height="200"   viewBox="0 0 500 200" >   <!--     📊 Render our graph bars as boxes to visualise our data.     This part is different for each graph, since each of them displays different sets of data.   -->   <g class="graph-data">     <rect x="10" y="20" width="10" height="80" fill="#e74c3c" />     <rect x="30" y="20" width="10" height="30" fill="#16a085" />     <rect x="50" y="20" width="10" height="44" fill="#16a085" />     <rect x="70" y="20" width="10" height="110" fill="#e74c3c" />     <!-- Render the rest of the graph boxes ... -->   </g>    <!--     Render our graph footer lines and labels.   -->   <use xlink:href="graph-footer" x="0" y="0" /> </svg>

And here is an updated <use> example with no visual change:

Problem solved.

What, you want proof? Let’s compare the demo with <use> version against the original one.

DOM nodes File size File Size (GZIP compression) Memory usage
No <use> 5,952 664 KB 40.8 KB 20 MB
With <use> 2,572 294 KB 40.4 KB 18 MB
Savings 56% fewer nodes 42% smaller 0.98% smaller 10% less

As you can see, the <use> element comes in handy. And, even though the performance benefits were the main focus here, just the fact that it reduces huge chunks of code from the markup makes for a much better developer experience when it comes to maintaining the thing. Double win!

More information


The post Too Many SVGs Clogging Up Your Markup? Try `use`. appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

, , , ,
[Top]

The Many Bad (and Good!) Patterns for Close Buttons

Manuel Matuzović details 10 bad HTML patterns for a close button. You know, stuff like this:

<a class="close" onclick="close()">×</a>

Why is that bad? There is no href there, so it really isn’t a link (close buttons aren’t links). Not to mention the missing href makes this “placeholder link” unfocusable. Plus, that symbol will be read as “multiplication” or “times”, which is not helpful (an “x” isn’t either).

What do you use instead?

There are plenty of good patterns too. If you prefer the visual look of a ×, then…

<button type="button">   <span class="sr-only">Close</span>   <span aria-hidden="true">×</span> </button>

…making sure you are accessibly hiding that close button.

Direct Link to ArticlePermalink

The post The Many Bad (and Good!) Patterns for Close Buttons appeared first on CSS-Tricks.

CSS-Tricks

, , , ,
[Top]

How many CSS properties are there?

Tomasz Łakomy posted a joke tweet about naming all the CSS attributes and Tejas Kumar replied with a joke answer, going as far as making an npm module. You can even run a terminal command to see them:

npx get-all-css-properties

You’ll get 259 of them. The source code uses the website quackit.com for the data, which I’d never heard of. 🤷‍♂️

I would have probably looked at MDN, where some quick querySelectorAll handiwork in the console yields a different number: 584. But ooops, that’s full of selectors, at-rules, and other stuff. Their reference only lists 72, but says it’s incomplete.

W3Schools lists 228 of them. HTML Dog lists 125. Our almanac has 176, and I know we omit stuff on purpose (e.g. we file margin-left under margin instead of making its own entry).

The horse’s mouth?

520 distinct property names from 66 technical reports and 66 editors’ drafts.

The post How many CSS properties are there? appeared first on CSS-Tricks.

CSS-Tricks

, ,
[Top]

So Many Color Links

There’s been a run of tools, articles, and resources about color lately. Please allow me to close a few tabs by rounding them up here for your enjoyment.

Curated colors in context

Happy Hues demonstrates a bunch of color palettes in the context of the site itself. That’s a nice way to do it, because choosing nice colors isn’t enough — it’s all about context. It can go bad, as the Refactoring UI blog demonstrates.

Dynamic, Date-Based Color with JavaScript, HSL, and CSS Variables

Rob Weychert shows off how he created date-based color schemes (so that every single day of the past 30 years would have a unique color scheme, each day looking slightly different than the day before).

Calculating Color: Dynamic Color Theming with Pure CSS.

Una Kravets creates color themes just with CSS. No JavaScript. No CSS preprocessing. Just Custom Properties, HSL colors, and some calc() in Calculating Color: Dynamic Color Theming with Pure CSS.

Color Tools

We’ve tweeted about color tools a lot. We’ve even threaded them up from time-to-time.

Visualizing Every Pantone Color of the Year

Adam Fuhrer took 20 years of top Pantone colors and matched them with wonderful photos. I love that the photos link to the personal sites of the actual photographers. It weirdly reminds me that you can browse Dribbble by color.

A Handy Sass-Powered Tool for Making Balanced Color Palettes

Stephanie Eckles blogged about using Sass to do math on colors to calculate and graph their luminance, saturation, and lightness, which can give you a by-the-numbers look to see if your color scheme is cohesive or not.

Leonardo

Leonardo is an interactive color palette tool that helps interpolate colors and generate variations based on contrast ratio.

Color Puns

Nice.

The post So Many Color Links appeared first on CSS-Tricks.

CSS-Tricks

, ,
[Top]

How Many Websites Should We Build?

Someone emailed me:

What approach to building a site should I take?

  1. Build a single responsive website
  2. Build a site on a single domain, but detect mobile, and render a separate mobile site
  3. Build a separate mobile site on a subdomain

It’s funny how quickly huge industry-defining conversations fade from view. This was probably the biggest question in web design and development1 this past decade, and we came up with an answer: It’s #1, you should build a responsive website. Any other answer and you’re building multiple websites and the pain from that comes from essentially doubling the workload, splitting teams, communication problems across those teams, inconsistencies across the sites, and an iceberg of other pain points this industry has struggled with for ages. As for the design of the website, you can use Candy Marketing’s Services.

But, the web is a big place.

This emailer specifically mentioned imdb.com as their example. IMDB is an absolutely massive site with a large team (they are owned by Amazon) and lots of money flying around. If the IMDB team decides they would be better off building multiple websites, well that’s their business. They’ve got the resources to do whatever the hell they want.

The post How Many Websites Should We Build? appeared first on CSS-Tricks.

CSS-Tricks

, , ,
[Top]

The Many Ways to Link Up Shapes and Images with HTML and CSS

Different website designs often call for a shape other than a square or rectangle to respond to a click event. Perhaps your site has some kind of tilted or curved banner where the click area would be awkwardly large as a straight rectangle. Or you have a large uniquely shaped logo where you only want that unique shape to be clickable. Or you have an interactive image that responds differently when different regions of it are clicked.

You can surround those assets with an un-styled <a> tag to get a clickable rectangle that’s approximately the right size. However, you can also control the shape of that region with different techniques, making sure the target for your click area exactly matches what’s visible on the screen.

SVG shapes

If your click target is an image or a portion of an image, and you have the ability to choose SVG as its format, you already have a great deal of control over how that element will behave on your page. The simplest way to make a portion of an SVG clickable is to add an an SVG hyperlink element to the markup. This is as easy as wrapping the target with an <a> tag, just as you would a nested html element. Your <a> tag can surround a simple shape or more complex paths. It can surround a group of SVG elements or just one. In this example the link for the bullseye wraps a single circle element, but the more complex arrow shape is made up of two polygons and a path element.

See the Pen
target svg
by Bailey Jones (@bailey_jones)
on CodePen.

Note that I’ve used the deprecated xlink:href property in this demo to ensure that the link will work on Safari. The href alone would have worked in Internet Explorer, Chrome, and Firefox.

The only trick here is to make sure the <a> tag is inside the SVG markup and that the tag wraps the shape you want to be clickable. The viewbox for this SVG is still a rectangle, so wrapping the entire SVG element wouldn’t have the same effect.

Image maps

Let’s say you don’t have control over the SVG markup, or that you need to add a clickable area to a raster image instead. It’s possible to apply a clickable target to a portion of an <img> tag using an image map.

Image maps are defined separately from the image source. The map will effectively overlay the entire image element, but it’s up to you to define the clickable area. Unlike the hyperlink element in the SVG example, the coordinates in the image map don’t have anything to do with the definition of the source image. Image maps have been around since HTML 3, meaning they have excellent browser support. However, they can’t be styled with CSS alone to provide interactive cues, like we were able to do with SVG on hover — the cursor is the only visual indicator that the target area of the image can be clicked. There are, however, options for styling the areas with JavaScript.

W3 Schools has an excellent example of an image map using a picture of the solar system where the sun and planets are linked to close-up images of those targets — everywhere else in the image is un-clickable. That’s because the coordinates of the areas defined in their image map match the locations of the sun and planets in the base image.

Here’s another example from Derek Fogge that uses uses maps to create more interesting click targets. It does use jQuery to style the areas on click, but notice the way a map overlays the image and coordinates are used to create the targets.

See the Pen
responsive image map demo
by Derek Fogge (@PositionRelativ)
on CodePen.

You can implement image maps on even more complex shapes too. In fact, let’s go back to the same target shape from the SVG example but using a raster image instead. We still want to link up the arrow and the bullseye but this time do not have SVG elements to help us out. For the bullseye, we know the X and Y coordinates and its radius in the underlying image, so it’s fairly easy to define a circle for the region. The arrow shape is more complicated. I used https://www.image-map.net to plot out the shape and generate the area for the image map — it’s made up of one polygon and one circle for the rounded edge at the top.

See the Pen
target image map
by Bailey Jones (@bailey_jones)
on CodePen.

Clip-path

What if you want to use CSS to define the shape of a custom click region without resorting to JavaScript for the styling? The CSS clip-path property provides considerable flexibility for defining and styling target areas on any HTML element.

Here we have a click area in the shape of a five-pointed star. The star is technically a polygon, so we could use a star-shaped base image and an image map with corresponding coordinates like we did in the previous image map example. However, let’s put clip-path to use. The following example shows the same clip-path applied to both a JPG image and an absolutely positioned hyperlink element.

See the Pen
Clip-path
by Bailey Jones (@bailey_jones)
on CodePen.

Browser support for clip-path has gotten much better, but it can still be inconsistent for some values. Be sure to check support and vendor prefixes before relying on it.

We can also mix and match different approaches depending on what best suits the shape of a particular click target. Here, I’ve combined the “close” shape using Bennet Freely’s clippy with an SVG hyperlink element to build the start of a clickable tic-tac-toe game. SVG is useful here to make sure the “hole” in the middle of the “O” shape isn’t clickable. For the “X” though, which is a polygon, a single clip-path can style it.

See the Pen
tic tac toe
by Bailey Jones (@bailey_jones)
on CodePen.

Again, beware of browser support especially when mixing and matching techniques. The demo above will not be supported everywhere.

CSS shapes without transparent borders

The clip-path property allowed us to apply a predefined shape to an HTML element of our choice, including hyperlink elements. There are plenty of other options for creating elements HTML and CSS that aren’t squares and rectangles — you can see some of them in The Shapes of CSS. However, not all techniques will effect the shape of the click area as you might expect. Most of the examples in the Shapes of CSS rely on transparent borders, which the DOM will still recognize as part of your click target even if your users can’t see them. Other tricks like positioning, transform, and pseudo elements like ::before and ::after will keep your styled hyperlink aligned with its visible shape.

Here’s a CSS heart shape that does not rely on transparent borders. You can see how the the red heart shape is the only clickable area of the element.

See the Pen
Clickable heart
by Bailey Jones (@bailey_jones)
on CodePen.

Here’s another example that creates a CSS triangle shape using transparent borders. You can see how the click area winds up being outside the actual shape. Hover over the element and you’ll be able to see the true size of the click area.

See the Pen
clickable triangle
by Bailey Jones (@bailey_jones)
on CodePen.


Hopefully this gives you a good baseline understanding of the many ways to create clickable regions on images and shapes, relying on HTML and CSS alone. You may find that it’s necessary to reach for JavaScript in order to get a more advanced interactive experience. However, the combined powers of HTML, CSS, and SVG provide considerable options for controlling the precise shape of your click target.

The post The Many Ways to Link Up Shapes and Images with HTML and CSS appeared first on CSS-Tricks.

CSS-Tricks

, , , , ,
[Top]