Dienstag, 30. September 2014

Responsive Images: If you’re just changing resolutions, use srcset.




CSS-Tricks





Responsive Images: If you’re just changing resolutions, use srcset.



If you're implementing responsive images (different images in HTML for different situations) and all you are doing is switching between different versions of the same image (the vast majority of usage), all you need is the srcset attribute on the <img>. Gaze upon this easy syntax:



<img src="small.jpg" srcset="medium.jpg 1000w, large.jpg 2000w" alt="yah">

It's not just the syntax that is easy, it does a better job than <picture> with <source>s with explicit media attributes (we'll cover why in a moment). Plus it has the opportunity to be much better in the future with browser settings and browser improvements.


I've screencasted about this before, but it clicked better watching Mat Marquis's talk at An Event Apart Austin and with Jason Grigsby's post. I'm writing about it again here because I think it's important for all of us to understand.


With srcset, the browser does the work of figuring out which image is best


In the simple example above, all we're doing is telling the browser about some images that we have available and what size they are. The browser then does all the work figuring out which one will be best.


Mat Marquis demonstrated this by showing how the browser approaches it with math. Say you're on a device with a screen width of 320px and is a 1x (non-retina) display. and the images you have are small.jpg (500px wide), medium.jpg (1000px wide), and large.jpg (2000px wide).


The browser goes:


Lemme do some quick math that nobody cares about except me.


500 / 320 = 1.5625
1000 / 320 = 3.125
2000 / 320 = 6.25

OK, so since I'm a 1x display, 1.5625 is the closest to what I need. It's a little high, but it's the best option compared to those other that are way too high.


Now another browser visits the site. It's also a 320px display but it's a retina (2x) display. That browser does the same math, only then goes:


OK, so since I'm a 2x display, I'm going to throw out that 1.5625 image because it's too low for me and might look bad. I'm going to use the 3.125 image.


See how that's already useful? You're letting the browser do the work of figuring out what's best for it rather than you trying to figure it out.


The browser is going to get smarter still


Remember there is already benefit to using srcset this way, but it's going to get better yet. Think of srcset as suggestions or just extra information to help a browser decide. Ultimately it can do what it thinks is right. That means:



  • A browser could offer user preferences regarding images

  • A browser could start factoring in bandwidth


Yes, theoretical, but likely.


And if you go down the <picture> with explicit sources, the browser has to do exactly what you say and not make choices for itself. Now, <picture> can be set up such that it does exactly what srcset it going to do right now, it's just a lot more verbose and doesn't leave room for improvement.


Also, sizes


We didn't talk about the sizes attribute at all here, on purpose. It's actually not that bad to just leave it off. In that case, it assumes sizes="100vw", which is saying:


I assume that when you use an image, it's going to be the entire width of the viewport.


That's usually not an awful assumption to make.


If you want, you can get all kinds of specific about it. You can use sizes to match your CSS layout exactly and tell the browser exactly how big that image is going to be on every screen size, matching how your breakpoints work in your design. That can get a little complicated and honestly it might be a little dangerous because you're putting CSS stuff in markup and you know how that goes. Eric Portis just wrote about this. Ideally it can be automated or injected server-side.


I also think kind of "generic" sizes attributes might be useful. On a kinda generic blog-ish site, maybe something like this is smart within content:


sizes="(min-width: 800px) 50vw, 100vw"


Meaning: "If the browser window is wider than 800px, this image is probably going to be displayed about half the size of that. If it's smaller, it'll probably be full-width."


Why talk about this?


Again: the vast majority of responsive images use isn't "art direction" based. Art direction is a fancy use case, and please do it to your heart's content. <picture> is great at that.


Most responsive images uses will be: "I have multiple versions of this graphic. Here they are, use the right one."


This is a very confusing subject. It needs to get thought about and written about so it can shake out and become a more ingrained part of our collective front end developer consciousness.


Tim Evko created a WordPress plugin for responsive images. It leverages WordPress's ability to make smaller versions of images. Then you click the image you want, and it ultimately outputs the responsive images code needed for it. At the moment, it uses <picture>. That's because
is up in the collective front end developer consciousness in a way stronger way that srcset. Tim is trying to understand all this so he can figure out if and how to change that plugin.




When?


This is tricky too.


If you want it right now and want great browser support, you need to polyfill it. But that has some potential downsides. So for now you'll have to make that call for yourself, I'm not sure there is a best practice for all scenarios yet.




Responsive Images: If you’re just changing resolutions, use srcset. is a post from CSS-Tricks








Montag, 29. September 2014

Thoughts on Pagination




CSS-Tricks





Thoughts on Pagination



I've had some disparate thoughts regarding pagination lately, so I thought I'd attempt to organize them in a post. That's how blogging works right?



Consistent Positioning


If there is any way to make sure your pagination buttons don't move, do it. It's such a nice experience to be able to just click-click-click (or tap-tap-tap) and the same thing happens each time. And when you get to the end, a subsequent click doesn't all the sudden to something different (because you're now clicking on a different button, or nothing).



If one button depends on the other for positioning, perhaps you could disable one and like opacity: 0.5; it to indicate its disabled-ness or even visibility: hidden; to hide it but still have it in the document flow.


Vertical positioning is important too. It's nice if the pagination buttons don't jump around based on the height of arbitrary content. If that's unavoidable, because, say, they are positioned below the bottom of arbitrary content, perhaps they buttons could be on top instead. Or in addition to, which is nice for content the requires scrolling.



Of course all situations are different, but perhaps even position: fixed; for some pagination elements would be useful to ensure those positions remain stable.


Text or no?


What is the pagination pagination past? (say that 10 times fast). The text in the buttons could help make that clear.


"Older"

"Newer"


"Next page"

"Previous page"


Mayyyybe. But what about:


"Less Relevant"

"More Relevant"


"Less Popular Content"

"More Popular Content"


While that may indeed be what the pagination is doing, that's kind of a bummer to say. I would tend to say: if the reason for pagination is fairly obvious or non-imperative, just use arrows.


Here on Dribbble, text is unnecessary. There is a web affordance that clicking that arrow is going to show more content.

One caveat to not displaying text is directionality. Will people enter your site on a page in which it is possible to paginate in either direction? If that's the case text might be appropriate, to orient people who didn't get the benefit of starting at a page in which you could only paginate in one direction.


Directionality


Speaking of arrows, which direction is most appropriate? I tend to find that most pagination begins with an arrow pointing to the right. (ala Google Search Results) I've heard this hotly debated with good points on both sides though. If you think of a timeline, that's almost always left-to-right and so paginating through time you'd think the arrow would point left if viewing the most recent content. But left arrows are associated with the back button, which is highly used and generally understood by users to mean going back to a previously visited area.



If there is a good chance a user might enter your site on a page in which you can paginate in either direction, I'd error on clarity and label the buttons.


URL Structure


Pagination often happens with URL's that go like:


website.com/page/1/

website.com/page/2/


That's not awful - at least it's clean. The trouble is that the URL doesn't contain any information about what is being paginated. But worse, the content on those pages can change. What is on page 1 today might be on page 3 tomorrow. That's super common in date-based pagination.


I've mused about this before.


Us web people are always really concerned with keeping URL's alive and hate it when URL's break. But isn't a URL that shows totally different content than when it was last referenced broken? It depends, and it might not be a fixable problem depending on the type of pagination being done. But it probably is fixable for date-based pagination. The current design of blogs on the Gawker network has pagination buttons that get you to URL's like:


lifehacker.com/?startTime=1411848000454

lifehacker.com/?startTime=1411749900413



Those URL's are more likely to have the same content on them over time, since it references content based on the publication time.


Depending on the publication frequency of your site, perhaps your pagination buttons could be months, weeks, or days, rather than arbitrary pages. Paginating back from a homepage of content might be like:


website.com/blog/

website.com/blog/2014/09/

website.com/blog/2014/08/


Then those URL's would always have the same content on them over time.


Even if you prefer using arbitrary chronological integer based pagination, wouldn't it make sense to reverse the numbers? Instead of 1, 2, 3 going back in time, have the numbers start at the highest for how much content you have.


website.com/blog/

website.com/blog/page/523/

website.com/blog/page/522/


I wonder why it's seemingly never done that way. Perhaps it involves the stress of count queries on older database systems?


Indication of how many, or no?


Speaking of count queries, should you indicate how much content there is to paginate through? In order to do that, you need to know how much there is, which involves some kind of count at some point.


<-    Page 1 of 302    ->


Is that useful. I might argue it is if the number could reasonably be useful. Either because you could look through it all, or because it gives you a sense of the breadth of your search, or because you might need that for use in an API, or something like that. It's probably not particularly useful somewhere like Google where it tells you it found eleventy-gillion results and it's really just showing off.


Other than just how many, should you be able to jump along further in the pagination?


[<-]    [1] ... [5] [6] [7] ... [302]    [->]


I dunno. I've always kinda baulked at pagination like this because it seems overly complex and marginally useful. Not to mention harder to honor consistent positioning. It does offer a way to jump to the start or end of pagination, which I could see being useful. It's just the longer versions that allow me to jump ahead like 4 pages (but not 6!) seem like they let a programmer little too close to the front end =).


Ajax


Pagination is the perfect kind of thing to do without a full page refresh, because it's highly likely the only thing changing on the page is the stuff being paginated. But this introduces some new complexities:



  • Do you append new content to the bottom of the current content area?

  • Is there a risk of so much content being added that the DOM weight slows down the page? Can you remove content at any point?

  • Do you replace all the content with new content?

  • If you do, should you scroll to the top of that new content? How do you do that across browsers?

  • Are you "losing" pageviews this way? Does that affect your business? Can you track this or do the same things that pageviews would have done for you anyway (e.g. rotate ads)?

  • Do you refer to the pagination differently, like "Load More Content"? Or is that inside baseball that only web workers care about?

  • Do you offer pagination in both directions this way?

  • Do the URL's change?

  • Can it be approached with progressive enhancement so pagination always works no matter what?


WordPress.com themes are leaning this way. I checked out a number of themes and they tend to have an "Older Posts" button that brings in new stuff Ajax style.



In this particular "Eighties" theme, there is no pagination at all without JavaScript. You can get to the content because there is links to the different months of content in the footer. Seems a little half-baked of an approach to me.


Consistency


Whatever you choose, be consistent about it across your entire site.


Lawd knows I need to implement some of these things of this across my sites.




Thoughts on Pagination is a post from CSS-Tricks








Donnerstag, 25. September 2014

The Game of Life




CSS-Tricks





The Game of Life



It's not really a "game" - but more like a set of rules by mathematician John Horton Conway. Imagine a grid of cells, like a spreadsheet or a <table>. Each cell is either alive or dead. "Rounds" pass one by one. In each round, there are rules on whether a live cell should continue to live or die, and if a dead cell should continue to be dead or become alive.



The Rules


It's sort of meant to replicate a real life environment. Cells can die either by underpopulation or overpopulation, and only live in perfect situations. The rules are pretty simple:



  1. Alive cell - Fewer than 2 alive neighbours - dies (underpopulation).

  2. Alive cell - 2 or 3 neighbours - continues to live (perfect situation).

  3. Alive cell - More than 3 alive neighbours - dies (overpopulation).

  4. Dead cell - Exactly three alive neighbours - becomes alive (reproduction).


Why are you talking about this?


I feel wicked nostalgic about it. A visual version of The Game of Life was the first programming project I ever did in High School. Or if not the first, the first one where I had an "Ah ha!" moment and realized programming and design could be super fun and interesting.


Give the problem to any programmer and they will likely solve it in a slightly different way.



  • What language should it be written in?

  • How do we architect it cleanly?

  • How can we make it computationally fast?

  • How big can we make it before it slows down?

  • How do we best store the data and states?

  • How are edges handled?


Give the problem to any designer and the results will look different.



  • What colors make sense?

  • Should we have different colors for states beyond alive and dead?

  • How big should the cells be to be interesting?

  • How fast should the rounds be to be interesting without being overwhelming?

  • Can you interact with it?

  • Can you go forward and backward in time?

  • How do you turn on and off cells? Clicking? Dragging? Randomization?

  • What are the most interesting shapes that can be made? Can we showcase those?


I also bring this up because I remember trying to make a demo a few years ago that was so awful that I'm jealous of all the cool ones. I basically used jQuery to query the DOM for neighbors of every single cell and it was so inefficient I probably should have been beaten with an antenna.


Examples


My first version was in Turbo Pascal on an old Apple. It brings me great pleasure to know that this little visual mathematical exercise is alive and well today, and people are using a tool I built to make versions. Even amongst demos that use the same technology, the approach can be different! I also have a collection.


JavaScript on Canvas


With a hint of jQuery:


See the Pen Conway's Game of Life by John H Moore (@john-h-moore) on CodePen.


Without:


See the Pen Game of Life by Qbit (@Qbit42) on CodePen.


See the Pen Game of Life on Canvas by Dennis Kerzig (@wottpal) on CodePen.


JavaScript on a <table>


See the Pen payKn by Alan R. Soares (@alanrsoares) on CodePen.


Backbone.js


See the Pen Conway's Game of Life in Backbone by Eric Miller (@SimpleAsCouldBe) on CodePen.


Using CSS box-shadow to draw cells


See the Pen box-shadow game of life by Joris van de Donk (@jorisvddonk) on CodePen.


In CoffeeScript


See the Pen mctCv by Hanganu Petru-Alin (@Lynku) on CodePen.


In D3.js


Fast!


See the Pen Game of Life - D3 by Reed Spool (@reedspool) on CodePen.




These are just front-end examples, but you can easily find examples in any language. Check out Golly for native app versions and the Wikipedia page for more information. One particularly interesting thing about The Game of Life is that all kinds of weird structures are possible that kind of "create life" or sustain it in weird ways.


One thing I've never seen is a Pure CSS version. Is it even possible? It would be wicked complicated with weird positioning and complex selectors. But they say Sass is "Turing Complete" so that means it's possible right? Or are other limitations at play there?


I'd be interested to see any more weird front end examples of The Game of Life. Or any stories you have about it from your past =).




The Game of Life is a post from CSS-Tricks








Dienstag, 23. September 2014

Don’t use `picture` (most of the time)




CSS-Tricks





Don’t use `picture` (most of the time)



Jason Grigsby:


Unless you're solving for art direction, you don't need to the
element. In fact, you're likely doing your users a disservice by using the <picture> element.


I'd wager that the majority of "responsive images" use is serving appropriately sized images for the situation. The situation = the size the image will be displayed at, screen pixel density, and bandwidth. That's exactly what <img sizes="" srcset=""> is best at. It does magical stuff that the browser can optimize for, whereas <picture> will only be as efficient as the rules you've explicitly set up for it (in which you almost surely weren't verbose enough with maximize efficiency). Only use the actual picture element when you need to do something very explicit (e.g. an exact breakpoint you need to swap out a totally different image).


Direct Link to ArticlePermalink



Don’t use `picture` (most of the time) is a post from CSS-Tricks








Sonntag, 21. September 2014

AMCSS




CSS-Tricks





AMCSS



"Attribute Modules for CSS"


An idea by Glen Maddern for moving styling with attributes rather than classes. Not an entirely new concept, but it's interesting to give it a name and explain a system based around it. Thoughts:



  • It avoids namespacing. Using modifiers like "large" is often a tempting naming convention, but too generic for a class name on its own. "Large" would be fine as an attribute value e.g. am-Button="large"

  • Cleaner on the HTML side, messier on the CSS side.

  • Probably technically slower CSS selectors, but that has been shown over and over to make very little difference except in extreme situations.

  • It probably makes the most sense while building a framework or pattern library that features variations. It's OK that these parts of your site would use an approach like this and your day-to-day styling doesn't.

  • I like how it sounds like caveman talk. <i am-Ogg="you jane.">


Direct Link to ArticlePermalink



AMCSS is a post from CSS-Tricks








Samstag, 20. September 2014

Build Web Layouts Easily with Susy




CSS-Tricks





Build Web Layouts Easily with Susy



I've been coming around to the idea of using Susy (a Sass add-on for grids) lately. I like the idea of grids-on-demand, rather than a strict framework (no matter how simple). We even added support to CodePen. Last week I ran into Eric Suzanne, the creator of Susy, and I told him Zell Liew was working on a guest post for this site. He was "Oh, Zell! Yeah he's awesome, he's like the unofficial promoter and trainer for Susy." And so, here's Zell introducing us to Susy!



Susy provides you with the tools to build your own grid layouts that match the needs of your website. She gives you the freedom and flexibility to build any design that you can imagine. It doesn't matter if your design has 5, 14 or 48 columns. Unequal width columns? Susy's got you covered.


Why would you pick Susy over the million other frameworks out there on the internet? You may never even heard of her before. What if her beauty is only skin deep?


Susy is one of the best things that happened to me in terms of my front-end development workflow over the past few months. She has helped me out so much that I decided to write a book about her to share her merits with the world. It's an in-depth guide on Susy and how you can use her to easily create any website design you want.


Still not convinced? Well then, all I ask is you give me the opportunity to try and change your mind through this article. We'll see why Susy is so special, and how she can help you out.


As they say, there's no substitute for experience, so I'm going to walk you through the Susy experience of creating a layout. And you can compare it with the experience of creating the same layout by hand (which involves calculating pixels...by yourself).


We'll start off simple, and progress on to more fancy layouts once you've gotten to know Susy a bit better.


Before we start, there are some things you must know about our friend, Susy. You MUST use the Sass preprocessor language for it, which means you have to at least know how to convert Sass into CSS. And no, you can't use LESS. Sorry, LESS folks!


Creating a Very Simple Layout


CSS-Tricks has a pretty straightforward layout, so let's use that for our first example.


Have a look at the blog and you'll find that CSS-Tricks is made up of two content areas: the main content and the sidebar area.


We'll assume CSS-Tricks uses a 12-column layout for the whole site, and it's content area takes up 8 of 12 columns while the sidebar takes up 4 of 12 columns. Quite standard stuff if you've worked with grids before.



If you have used Bootstrap or Foundation before, the markup for this site layout would be:


<div class="wrap">
<div class="content col-md-8"></div>
<div class="content col-md-4"></div>
</div>

Simple, yes. But Bootstrap and Foundation also come with a lot of baggage, that a lot of the time, we just don't want to deal with. If you don't need most of the other stuff that comes with Bootstrap and Foundation, Susy would be a much better fit for you.


A stoic developer who hand-codes all his sites from scratch, no frameworks or frills, would probably write his mark-up like so:


<div class="wrap">
<div class="content">Content</div>
<div class="sidebar">Sidebar</div>
</div>

To create an 8-column content and 4-column sidebar, you'll have to measure widths of the content, the gutter and the sidebar. One rule of responsive web development is to output these widths in percentages, so you'll have to convert them accordingly.



So the corresponding CSS would probably look something like this:


/* I tend to use border-box sizing for all my web layouts. */
*, *:before, *:after {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}

.wrap {
max-width: 1120px;
}

/* Clearfix for floated children */
.wrap:after {
content: &quot; &quot;;
clear: both;
display: block;
}

.content {
float: left;
width: 66.071429%; /* 740px / 1120px */
margin-right: 1.6964286%; /* 19px/1120px */
}

.sidebar {
float: right;
width: 32.2321429%; /* 361px / 1120px */
}

A quick note before we continue further: I love to set the box-sizing property to border-box for all of my web elements, and I highly recommend you do the same as well. Chris has written extensively about box-sizing here.


Anyway, the hand-coding from scratch method can start to get tedious if you have multiple layouts to work with. Imagine calculating all those percentages every single time!


That's precisely what Susy helps you with. She does the math for you.


Creating the Simple Layout With Susy


When using Susy to create any layout, you'll first have to let her know what settings you want her to use. There are a whole bunch of default settings that Susy uses to kickstart every project.


I'm assuming this is your first experience with Susy, so we'll stick with most of the defaults for now. You do need to change two properties though, and you change them by declaring them on the $susy map.


At the same time, let's also apply the border-box property like we have done above.


@import "susy"

/* Changing Susy default global settings */
$susy: (
/* Tells Susy to use 12 columns */
columns: 12,
/* Tells Susy to use border-box */
global-box-sizing: border-box
);

/* Makes border-box properties */
@include border-box-sizing;

This time round, instead of manually calculating the exact pixels and percentages for the layout, we're going to tell Susy to do it for us. To do this, you'll just have to tell Susy that content is 8 columns and sidebar is 4 columns.


We do have to let Susy know that sidebar is the last item on the row so it can make the necessary adjustments to minimize the effects of browser subpixel rounding errors.


/* Tells Susy there's 8 columns in the content */
.content {
@include span(8);
}

/* Tells Susy there's 4 columns in the sidebar, and its the last item on the row. */
.sidebar {
@include span(4 last);
}

This compiles into:


*, *:before, *:after {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}

.wrap {
max-width: 1120px;
margin-left: auto;
margin-right: auto;
}
.wrap:after {
content: &quot; &quot;;
display: block;
clear: both;
}

.content {
width: 66.10169%;
float: left;
margin-right: 1.69492%;
}

.sidebar {
width: 32.20339%;
float: right;
margin-right: 0;
}

Did you notice that the CSS output is exactly what we needed to create? Susy sure saved us a lot of time.


We're not done with the CSS-Tricks layout yet though. If you scroll down to the bottom of the site, you'll find the social media area, and you can also see that there are 10 social media items within this area:



If you use a traditional grid framework in your design, you're pretty much in trouble. As far as I know, there's really no simple way to quickly manipulate the number of columns from 12 to 10 using frameworks like Bootstrap or Foundation without affecting the rest of the layout.


Susy doesn't bind you with such rules. You are free to create your own rules. After all, it's your grid.


Your Grid, Your Rules


Anything is possible when you're making your own grids. Before we move on to the CSS, let's first get the mark-up correct. It should look something like this:


<div class="wrap">
<div class="content"></div>
<div class="sidebar"></div>
<div class="social">
<ul>
<li class="social__list-item"></li> <!-- repeat 10x -->
</ul>
</div>
</div>

Now we can begin work on the CSS. Using the hand-coding approach, you may have realised you'll have to calculate the width of each item and gutter again.



.social {
padding: 1.6964286% /* 19px / 1120px */
}

/* Adds clearfix to social to prevent the float collapse */
.social:after {
content: &quot; &quot;;
clear: both;
display: block;
}

.social__list-item {
float: left;
width: 9.1497227; /* 99px / 1082px */
margin-right: 1.0166359; /* 11px / 1082px */
}

/* And the last item cannot have any right margins */
/* It is also good to float it right to mitigate subpixel rounding errors */

.social__list-item:last-child {
float: right;
margin-right: 0;
}

It feels like quite a tedious job, if you ask me.


It's so much simpler if we get Susy to do it for us. You'll just have to tell Susy that there are 10 columns in all (instead of 12), and each social item takes up one column.


.social {
/* Adds a padding of 19px to each side of the .social container */
padding: gutter();
/* Adding a clearfix because all children elements are floated */
@include cf;

.social__list-item {
/* Telling Susy that there are 10 items, and each takes up 1 row */
@include span(1 of 10);
/* Another way to tell Susy that this is the last item in the row */
&:last-child {
@include last;
}
}
}

And Susy produces the same exact CSS properties that we need for the grid!


.social {
padding: 1.69492%;
}

.social:after {
content: "";
display: table;
clear: both;
}

.social .social__list-item {
width: 8.16327%;
float: left;
margin-right: 2.04082%;
}

.social .social__list-item:last-child {
float: right;
margin-right: 0;
}

This is how simple it can be to use Susy. Math skills not required. As long as you know how to make a grid with vanilla CSS, you will know how to use Susy.


One thing about working with percentages is the inevitable fact that your output will contain subpixels, like 10.4px. This has been a major problem with layouts for a very long time because different browsers treat these subpixels differently.


For instance, webkit browsers round these pixels down, and 10.4px will be rounded down to 10px. The larger the number of items in your layout, the larger the occurrence of each rounding error. So our 10-item error is clearly showing up in webkit browsers.



Such errors are unbecoming and we simply cannot have that.


Dealing With Subpixel Rounding Errors


One method is make sure the percentages don't generate subpixels at all. But

that's not a good idea because and you're going to be stuck with either a non-responsive website, or one that snaps to different grid widths.


There's another method, which I call the Isolate Technique.


This method is slightly more advanced and requires you to know more about laying out elements with the isolate technique that was developed by John Albin Wilkins. This technique has been used in the battle-tested zen grids for a long time. If you're familiar with Zen grids, you'll know what I'm talking about here.


If not, let's examine how to use this technique.


The Isolate Technique


The premise of the isolate technique is to reduce the compounding effects of rounding errors by positioning them right where they should be with specific margins.


The requirements of using this technique are:



  1. Each element must have a margin-left property to position itself in the correct position.

  2. Each element must have a margin-right property of -100% to pull the next item to the extreme left edge of the container.


This technique can be quite confusing if you're not familiar with how negative margins. Let's go through a full step-by-step explanation on how it works.


Say you need to create a 3-column layout:



We'll go through the positioning of each item one-by-one. Item 1 is quite straightforward.



  1. It has a margin left of 0, so it sits on the start line.

  2. Then it pulls the next item (Item 2) back to the start line with a margin-right of -100%.



Item 2 has been pulled to the start line by Item 1 before it's own CSS properties kick in.



Item 2 then positions itself with a margin-left property that is the percentage value of up 2 columns and 2 gutters, positioning it exactly on the third column.



Item 2 also has a margin-right property, which pulls the next item (Item 3) to the start line.



Item 3, gets pulled to the start line by Item 2 before its own CSS properties kick in.



It is then positioned on the 5th column by its margin-left property that is a percentage value of 4 columns and 4 gutters.



And it pulls the next item to the start line and the pattern repeats itself for the number of items in total.


If any item needs to start on a new line, it has to clear the float from its previous item with the clear: left property.



And to align it to with the first column (positioned on the start line), it has to change its margin-left property back to 0 to place itself there.



That's how the Isolate Technique work. Now that you understand it, we can use it to deal with the subpixel rounding issue.


Solving Subpixel Rounding Errors


We have to position each item manually with the isolate technique, and Susy can help us with that.


Susy has a convenience function that helps you skip ALL the manual stuff. It's called the gallery mixin.


.social__list-item {
@include gallery(1 of 10);
}

And the CSS it outputs uses the isolate technique mentioned above.


.social__list-item:nth-child(10n + 1) {
margin-left: 0;
margin-right: -100%;
clear: both;
margin-left: 0;
}
.social__list-item:nth-child(10n + 2) {
margin-left: 10.20408%;
margin-right: -100%;
clear: none;
}
.social__list-item:nth-child(10n + 3) {
margin-left: 20.40816%;
margin-right: -100%;
clear: none;
}
.social__list-item:nth-child(10n + 4) {
margin-left: 30.61224%;
margin-right: -100%;
clear: none;
}
.social__list-item:nth-child(10n + 5) {
margin-left: 40.81633%;
margin-right: -100%;
clear: none;
}
.social__list-item:nth-child(10n + 6) {
margin-left: 51.02041%;
margin-right: -100%;
clear: none;
}
.social__list-item:nth-child(10n + 7) {
margin-left: 61.22449%;
margin-right: -100%;
clear: none;
}
.social__list-item:nth-child(10n + 8) {
margin-left: 71.42857%;
margin-right: -100%;
clear: none;
}
.social__list-item:nth-child(10n + 9) {
margin-left: 81.63265%;
margin-right: -100%;
clear: none;
}
.social__list-item:nth-child(10n + 10) {
margin-left: 91.83673%;
margin-right: -100%;
clear: none;
}

And the social media area is back to normal!



Now that we've built up some momentum, let's take it up a notch and make the layout responsive.


Making the Layout Responsive


Responsive websites have became increasingly important and I'll be selling you short if I didn't talk about how to make responsive layouts with Susy.


The very first step to creating responsive layouts is to make sure that you're familiar with how media queries work. Pay special attention to the Mobile-First media queries in that article as we're going to be using them.


For simplicity's sake, let's only create a layout with two breakpoints - one for the mobile view that begins at 0px and ends at 700px; and another for the desktop view that begins at 700px.


In the mobile view, both the .content and .sidebar sections take up a full 100% of the viewport. After 700px, .content and .sidebar will be split into 8 columns and 4 columns respectively.


If you hand code it, this is what it might look like (using Sass):


.content {
/* Styles for mobile view go here */

/* Styles for desktop view go here */
@media (min-width: 700px) {
width: 66.10169%;
float: left;
margin-right: 1.69492%;
}
}

.sidebar {
/* Styles for mobile view go here */

/* Styles for desktop view go here */
@media (min-width: 700px) {
width: 32.20339%;
float: right;
margin-right: 0;
}
}

You don't need to create any styles for the mobile view because <div> blocks takes up 100% width by default. What you need, however, is to make sure the desktop layout kicks in once the viewport hits 700px.


Coding a responsive layout by hand is the same as coding a responsive layout with Susy, only Susy makes things faster. You use the exact the same technique and media queries.


.content {
/* Styles for mobile view go here */

/* Styles for desktop view go here */
@media (min-width: 700px) {
@include span(8);
}
}

.sidebar {
/* Styles for mobile view go here */

/* Styles for desktop view go here */
@media (min-width: 700px) {
@include span(4 last);
}
}

So that's it for .content and .sidebar.


The next bit is the social media section. This is how it looks like in the mobile view.



Instead of having each item take up 1 of 10 columns, each item now takes up 2 of 10 columns on the mobile view, and you can do this by using span(2 of 10).


Note: You might be wondering why not use 1 of 5 columns instead. There are slight nuances between span(1 of 5) and span(2 of 10), and a picture best explains it:



These are fundamentally different layouts because of the number of gutters involved. You can always use the 1 of 5 option but I'll stick with 10 because the size of the gutters are then much closer to 12.


We'll call the gallery mixin again, and add one gutter below each item to provide some separation between the rows.


.social {
/* ... Same styles as above */

.social__list-item {
@include gallery(2 of 10);
margin-bottom: gutter(10);
}

@media (min-width: 700px) {
@include gallery(1 of 10);
margin-bottom: 0;
}
}

Here's an example of what we have done so far:


See the Pen eidcj by Zell Liew (@zellwk) on CodePen.


Working with Susy is just like working with vanilla CSS. The key difference is that Susy is a math-whiz.


Susy is so good at math that she can allow you to create wacky asymmetric grids that have columns of different sizes.


Let's try creating the layout for CSS-Tricks using an asymmetric grid.


Making The Layout With Asymmetric Grids


Declaring columns is a tiny bit different when working with asymmetric grids. You tell Susy the number of columns and the ratio of their sizes with a Sass list. Since CSS-Tricks has content that is twice the width of the sidebar, the columns can be represented by a 2 1 list. This means that there are two columns, one of them is twice the width of the other.


You'll also have to set the output mode to isolate on Susy's global settings:


$susy : (
columns: 2 1,
output: isolate,
)

Instead of saying content has 8 columns now, we say that content has 1 column. Susy is smart enough to know the size of the column if you tell her its location. In this case, content is the first item.


.content {
@include span(1 first);
}

Likewise, you'll have to let Susy know how many columns sidebar takes up and where it is located. In this case, sidebar takes up the second column, which coincidentally is also the last item on the row.


.sidebar {
@include span(1 last);
}

This is how it will look:



There is a lot more to asymmetric grids and it would take a whole new article to show you how to build them with Susy. I've have created a simple design that explains the concepts of asymmetric grids on my blog that uses the following as an example.



In addition, I wrote about creating an asymmetric layout comprehensively in Learning Susy with a more realistic example that was based on Nathan Ford's design. You may want to grab the book if you want to find out more about it.



Conclusion


Well, we've reached the end of this introduction to Susy, as well as some peripheral (but important) matters like subpixel rounding errors. I hope you are at least a little bit convinced to give Susy a try.


In fact, there is so much more to Susy than what I could cover here. So I'm going to refer you to 5 sample chapters of my book on Learning Susy. Have a read through and you'll learn how you can use Susy to do so much more. Also, if you have any questions about Susy, or just front-end development in general, feel free to contact me.




Build Web Layouts Easily with Susy is a post from CSS-Tricks








Freitag, 19. September 2014

The Bézier Game




CSS-Tricks





The Bézier Game



A game to help you master the pen tool.


By Mark MacKay.


Early in my career I had a job where a good half of it was cutting detailed clipping paths on photos (using the Pen Tool in Photoshop). We had an in-house photography department that shot furniture and electronics and the like, and I had to cut outlines around everything so designers could easily isolate things as needed. I'm sure I did thousands of photos. I'm still not a super expert, but I value my Pen Tool skills and end up using them regularly.


Direct Link to ArticlePermalink



The Bézier Game is a post from CSS-Tricks








Donnerstag, 18. September 2014

Scroll-Then-Fix Content




CSS-Tricks





Scroll-Then-Fix Content



A reader sent me in a GIF showing off a cool effect they saw on Google on mobile. (Presumably the homepage you see when you launch Chrome on Android?) There is a search input in the middle of the page that scrolls with the page, but as it's about to scroll off the page, it becomes affixed to the header. Let's cover that, because, you know...




It's a cool effect particularly if used to make UX better and not to affix some dumb intrusive ad. Here's the GIF I based the idea on. Little choppy, but the idea is there:



Two States


Like most good tricks, there isn't much to it. All we do is think of (and design for) the two different possible states:



  1. Search bar in its scrollable position

  2. Search bar in its fixed header position


We toggle between them simply by changing a class name. There is no trickery with having two search forms that reveal themselves in different scenarios. That's good, as we don't want to smurf around with keeping those in sync. Much easier to just move a single one around.


State One



(I'm going to use SCSS here because the nesting is nice for managing states.)


.top-header {
position: fixed;
top: 0;
left: 0;
width: 320px;
height: 60px;
}

.search { /* Container just in case we want more than just the search input to come along */
position: absolute;
top: 155px;
left: 20px;
right: 20px;
input {
width: 265px;
transition: width 0.2s;
-webkit-appearance: none; /* Autoprefixer doesn't catch this */
}
}

.top {
height: 250px; /* Space in here for search */
padding-top: 40px;
position: relative;
}

State Two



Assuming we've put a class of "fix-search" on a parent element.


.top-header {
...
.fix-search & {
background: #eee;
}
}

.search { /* Container just in case we want more than just the search input to come along */
...
.fix-search & {
position: fixed;
top: 10px;
input {
width: 250px;
}
}
}

Switching States


The trick here is applying that class at just the right moment. In our little demo, we can just test for when that perfect moment would be and hard code that into some JavaScript watching for scrolling. jQuery style:


var wrap = $("#wrap");

wrap.on("scroll", function(e) {

if (this.scrollTop > 147) {
wrap.addClass("fix-search");
} else {
wrap.removeClass("fix-search");
}

});

That's all it takes to switch between the two states we've set up. If the page has scrolled down 147 pixels or more, it will have that class applied. If not, it doesn't. Even if you go down and come back up the class will go away (because this little function gets called on every scroll event).


Demo


See the Pen Search Box in Content Moves to Fixed Header by Chris Coyier (@chriscoyier) on CodePen.


Debouncing


In the grand tradition of mentioning scroll debouncing whenever any demo binds an event to a scroll event: you should consider debouncing when binding functions to scroll events, because if you don't, it'll get called a zillion times and could be slow.


CSS


This is the kind of thing that would be sweet to do in CSS alone. No great solutions pop to mind just yet, but I'm continually amazed by crazy things people use CSS to do, so if something comes along I'll update this.


Perhaps someday we'll be able to do scroll position media queries?


Fixed Position Support


Note that this demo relies on fixed positioning, which has a sketchy history on mobile. While I'm tempted to say it has "pretty good" support these days, you should make the judgement yourself. Some reading:



This is just one (not particularly reusable) example


There are a lot of magic numbers in this demo. Anytime you are setting heights there should be some warning flags happening up in your brain. It doesn't mean never do it, it just means be warned. In this demo, if that centered image in the header changed height, it would look weird pretty much no matter what. This isn't the most flexible and forgiving of layouts as it is. Even if you fixed the header to look right after a change, the JavaScript has corresponding magic numbers for when to change state.


Perhaps some version of using waypoints (or the concept of it) could make a more bulletproof system.




Scroll-Then-Fix Content is a post from CSS-Tricks








Mittwoch, 17. September 2014

Getting Started with CSS Shapes




CSS-Tricks





Getting Started with CSS Shapes



I just watched Jen Simmons give a talk Modern Layouts: Getting Out Of Our Ruts and she had some great examples of how easy CSS shapes are to use, even with safe progressive enhancement. If you haven't heard of them, essentially it's a way to wrap content (typically text) around custom SVG-like paths.


As serendipity would have it, here's Razvan Caliman with a megapost on how it all works and how to use it with real examples.


Direct Link to ArticlePermalink



Getting Started with CSS Shapes is a post from CSS-Tricks








Dienstag, 16. September 2014

A Look at SVG Light Source Filters




CSS-Tricks





A Look at SVG Light Source Filters



The following is a guest post by Joni Trythall. Joni recently finished a Pocket Guide to Writing SVG. I've been excited about SVG for a while now, working with it, learning about it, writing about it... but there is so much to know. It really is another whole universe of the web. So I reached out to Joni to see if she would like to write something for CSS-Tricks on SVG and she agreed! Here's Joni on lighting in SVG, something I know I knew nothing about before reading this.



SVG has its own set of filter effects that, when writing SVG, allow the author to combine several of these effects and apply the filter to the graphic.


Some of the more fantastic features of SVG filtering revolve around the light source. You can apply a lighting effect to SVG and then control the details of that through one of three filter effects: fePointLight, feDistantLight, and feSpotLight.


These light source filters allow for some especially neat capabilities. Check out this shiny, lighted apple (as compared to a non-lighted one):


See the Pen 7d39edca68f2d2b2dfe0e7f3728a276a by Joni Trythall (@jonitrythall) on CodePen.


In this post we will review the basic syntax for SVG filters, dive into some of the more common attributes, look at lighting source effect options, and then bring everything together with an SMIL animation experiment.


filter Element


SVG filter details reside within a <filter> element. A <filter> is comprised of several different effects and these effects are then all applied to a graphics element (such as a rectangle, <rect>) or container element (such as a group, <g>).


<svg>
<defs>
<filter id="apples">
< (filter effect) />
< (filter effect) />
</filter>
</defs>
<rect filter="url(#apples)" />
</svg>

Select Attributes


While there are a great number of filter related attributes, we will specifically be focusing on the ones used here throughout the apple demos.


The following attributes, with the exception of in, are able to be used within any SVG filter effect.


x, y


The x and y attributes within filters set the minimum coordinates on the appropriate axis for the region in which the filter will take place.


result


The result attribute assigns a name to a specific filter effect. This effect can then be referenced by another effect to follow through the in attribute. Both effects must reside within the same <filter> and it allows us to combine several filter effects into one to be applied to a graphic.


A result value is not required, but is useful when looking to reuse specific effects. While its purpose closely resembles that of an id, result values are only useful within the same <filter> element and are therefore not accessible anywhere else in the document.


in


The in attribute specifies the input for a specific filter effect. There are seven value options here, including the name of the result which we just reviewed in the previous section, but perhaps the most frequently referenced are SourceGraphic and SourceAlpha.


If the in attribute is left unspecified and the filter effect is the first listed within the <filter> then it will default to SourceGraphic. Alternatively, if this attribute is left unspecified and is not the first effect listed, then the default will inherit the value of the effect before it.



  • A SourceGraphic value within in sets the input for the filter as the RGB colors of the graphical element to which it is being applied.

  • The SourceAlpha has the same impact as SourceGraphic except black color values are used for the RGB channels input.


Here is a look at the impact these two values have when applying a blurred filter to two identical circles, both having a fill value of #ED6E46:



Lighting Source Filters


Now that we have a familiarity with some of the more common attributes used within SVG filters lets focus on the lighting source effects.


SVG lighting is accessed through the use of feDiffuseLighting or feSpecularLighting filters, which establish its calcluations based on the appropriate component of the Phong lighting model (PDF).


While diffuse light is light that hits a surface and gets scattered equally in all directions, specular light refers to a bright spot of light that gets reflected in a particular direction. The demos throughout this post will only focus on lighting effects accessed through specular light, or feSpecularLighting, or "light that makes all the things look shiny!".


Attributes used within this filter effect, such as specularConstant and specularExponent, set the details of the light based on Phong lighting model calculations.


The basic light filter related syntax going forward will look like this:


<filter>
<feSpecularLighting>
< (light source effect) />
< (light source effect) />
</feSpecularLighting>
</filter>

Let's take a look at the fePointLight, feDistantLight, and feSpotLight effects that will reside within this specified calculation.


fePointLight


fePointLight establishes a specific point as the main light source when applying the feSpecularLighting filter and is how the shiny apple was achieved in the very first demo.


The appearance of the light not going to the very edge of the apple is created by the value of the feGaussianBlur effect, and a higher value here would create greater blending.


x, y, z


The x, y, and z attributes here determine the location of the light source in the coordinate system on the appropriate axis. z will adjust the perceived size of the point of light by determining its location from the point to the user; a higher value here results in a larger point of light that is "closer" to the user.


feDistantLight


feDistantLight defines a distant light source.



  • The azimuth attribute within feDistantLight defines the clockwise direction angle in degrees for the light source on the XY plane.

  • The value within `elevation` defines the direction angle in degrees of the light source from the XY plane towards the z axis.


The filter on the apple below has an azimuth value of 25px and an elevation value of 40px:


See the Pen 9be1624ee991e2978a922ac39b8bb029 by Joni Trythall (@jonitrythall) on CodePen.


feSpotLight


feSpotLight defines a spot light as a light source.



  • The x, y, and z values establish the location of the light source along the appropriate axis within the coordinate system.

  • The limitingConeAngle restricts the area to which light is projected by disallowing light to render outside of it. This value sets the angle in degrees between the spot light axis and cone. A higher value here results in a less restricted area.


The feSpotLight filter below contains the following specifications: x="400" y="400" z="900" limitingConeAngle="9":


See the Pen 195ed2b4fa8f17b0f8145b9384116a44 by Joni Trythall (@jonitrythall) on CodePen.


Animating Light Sources


Light sources can also be animated. The code for this graphic is fairly complex and lengthy when used inline, but for the sake of science we are going to have the sun moving from one side of the apple tree to the other acting as a "light source".


See the Pen Apple Tree Lighting Animation by Joni Trythall (@jonitrythall) on CodePen.


The sun, aka our pretend light source, is moving across the screen through SMIL animations. In turn, the light source filter on the tree is also being animated in response to the sun's positioning.


An <animate> element must reside within each element to be animated, which are both noted in the HTML.


Conclusion


SVG light source filters can really bring a graphic to life on the screen, testing the boundaries of the two-dimensional limitations of the language. These advanced features allow us to create more complex and detailed images that live within the DOM and can easily become interactive or scripted.


The lighting details addressed here really only scratch the surface concerning the capabilities of SVG filters, but hopefully what we have reviewed inspires you to tinker with it and explore its full potential.


In this post we reviewed some basic <filter> syntax, took a look at a few attributes, focused on some neat lighting sources effects, and then animated these effects in the name of science.




Editor's note: Make sure to check out Joni's Pocket Guide to Writing SVG.




A Look at SVG Light Source Filters is a post from CSS-Tricks








Montag, 15. September 2014

Sponsor: Hack Reactor – New Remote Beta Classes




CSS-Tricks





Sponsor: Hack Reactor – New Remote Beta Classes



With the success of their first online cohort, Hack Reactor is happy to announce two new Remote Beta classes. Aspiring engineers no longer need to relocate to San Francisco in order to attend their 12-week immersive JavaScript coding school. Take Hack Reactor’s program from home and gain the skills and confidence needed to build amazing products.


Remote Beta Classes begin October 27th & December 8th with recommended application deadlines of September 29th and November 10th, respectively. Apply today and take their exceptional Remote Beta program from wherever you are!


Direct Link to ArticlePermalink



Sponsor: Hack Reactor – New Remote Beta Classes is a post from CSS-Tricks








Mittwoch, 10. September 2014

Give Designers Tools To Get You What You Need




CSS-Tricks





Give Designers Tools To Get You What You Need



Let's say you're having a health back-and-forth between you, a front end developer, and a designer. All the best work comes through collaboration and iteration, right? I believe that. But I also believe there are time traps in there. If you feel you're wasting time by getting peppered with tiny design tweaks, there might be salvation in giving designers tools to do the tweaks and then give you exactly what you need.


Let's see some simple examples.



Positioning Elements in a Space


Let's say you have some absolutely positioned elements. Their exact position is a big part of how the design feels. You could hook up a script to allow those elements to be dragged, and then report their position with the exact CSS you'll need to put them there.


Here I've used David DeSandro's Draggabilly to do that:


See the Pen Draggable Elements that Report their Position in CSS by Chris Coyier (@chriscoyier) on CodePen.


It's a fairly small little script that allows elements to be dragged, and when a drag event stops, it creates the little bit of CSS needed based on that elements ID and top/left position, and puts that in the bottom right corner of the document ready for copy-pasting and providing to you, the front end developer.


Changing Font Stuff


How about little <select> that comes up over paragraphs that allows you to toggle between font families in development?



Or perhaps a range input that controls line-height:



Like this.


Color Pickers


Wouldn't be too difficult to drop in a color picker that shows up around elements you choose and changes backgrounds, fills, borders, strokes, text color, etc.




JSColor


DevTools Training


Of course building your own tools is great because:


They can be designed just how you like them

You can build them to change anything whatsoever

They can be integrated directly onto the design


But... they are a bunch of work as well. You will likely get quite a bit of mileage out of just showing a designer how to use a browsers DevTools to tweak designers. Chances are, they will really take to it.



Have you ever done this?


While I prefaced the article with the idea that this could be time saving for the developer, since you're giving designers tools in which to express exactly what they want, it could backfire. Meaning you could spend a ton of time on these little tools only to see them used very little. Communication, as always, is key.


Have you ever tried doing something like this in your team workflow?




Give Designers Tools To Get You What You Need is a post from CSS-Tricks








Montag, 8. September 2014

Glitch Effect on Text / Images / SVG




CSS-Tricks





Glitch Effect on Text / Images / SVG



Lucas Bebber's Glitch is a super cool effect. It's like you're looking at some text displayed on a progressive scan monitor that has been dropped on the ground one too many times and so the alignment of the pixels is off in weirdly un-even amounts time and space.


It's bonafide CSS trick if there ever was one! It took me a bit to figure out how it was working, so I thought I'd explain. Then I ended up making it work for other kinds of content as well as making it into a group of Sass @mixins to make working with it a bit easier.



See the Pen CSS Glitched Text by Lucas Bebber (@lbebber) on CodePen.


Three Copies of the Text


While the HTML is just:


<div class="glitch" data-text="GLITCH">GLITCH</div> 

Three copies of it are created, via pseudo elements, and they are positioned right on top of each other.


.glitch {
position: relative;
}
.glitch::before,
.glitch::after {
content: attr(data-text);
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}

Producing three unique copies that can be controlled individually:



Alter the Copies


Each copy is identical except that:



  • It's offset to the left or right

  • It has a highlight, in the form of a text-shadow


Between the offset and the highlight, it gives it that broken feeling.


.glitch::before {
/* ... anything needed to make it identical */

/* variation */
left: 2px;
text-shadow: -1px 0 red;

/* important: opaque background masks the original */
background: black;
}
.glitch::after {
/* ... anything needed to make it identical */

/* variation */
left: -2px;
text-shadow: -1px 0 blue;

/* important: opaque background masks the original */
background: black;
}

So now the three copies are like this:



Clipping the Copies


You'd only ever see the top copy if left as-is. Probably the ::after version, unless you alter with z-index. But never fear, we're going to be only revealing parts of the top, altered copies with the clip property. This property is apparently deprecated in favor of clip-path, but at the time of this writing, only clip was working for me. I'm sure that will change in time, so we'll have to keep an eye on it, and presumably Autoprefixer will handle it.


The syntax for clip is kinda weird. For the four values, you might expect something like top/left/width/height, or point-at-top-left/point-at-bottom-right. But instead it's like margin and padding: top/right/bottom/left


.glitch::before {
clip: rect(44px, 450px, 56px, 0);
/*
Essentially a box from 0, 44px
to 450px, 56px
*/
}

Here's some example clips on those layers, now with fully opaque backgrounds applied (but still rotated and with extra colors so you can see what's going on):



Animate the Clips


Turns out clip can be animated, so, that clipped box will animate to a new position over time if told to, Here's an example of keyframes:


@keyframes glitch-anim {
0% {
clip: rect(70px, 450px, 76px, 0);
}
20% {
clip: rect(29px, 450px, 16px, 0);
}
40% {
clip: rect(76px, 450px, 3px, 0);
}
60% {
clip: rect(42px, 450px, 78px, 0);
}
80% {
clip: rect(15px, 450px, 13px, 0);
}
100% {
clip: rect(53px, 450px, 5px, 0);
}
}

Notice the left and right values remain the same, it's just the top and bottom that change. And those values are kinda random.


You can generate that pretty easily with Sass, like:


@keyframes glitch-anim {
$steps: 10;
@for $i from 0 through $steps {
#{percentage($i*(1/$steps))} {
clip: rect(random(100)+px, 9999px, random(100)+px, 0);
}
}
}

Because you'd want two sets of randomized clipping positions, you'd make two sets of those @keyframes, and apply them to the copies:


.glitch::before {
...

animation: glitch-anim-1 2s infinite linear alternate-reverse;
}

.glitch::after {
...

animation: glitch-anim-2 2s infinite linear alternate-reverse;
}

There is where we set the speed (number of keyframes also affects speed) as well as making it run infinitely back and forth.


It's pretty fun to watch:



Although it should go without saying a little goes a long way.


Sass @mixins


I thought it would be neat if the technique was more reusable. Basically call a @mixin with parameters to control the effect and get just what you need.


.example-one {
font-size: 100px;
@include textGlitch("example-one", 17, white, black, red, blue, 450, 115);
}

Here's my take on it:


/*
(TEXT) PARAMS
=================
1. Namespace
2. Intensity
3. Text color
4. Background color (flat)
5. Highlight #1 color
6. Highlight #2 color
7. Width (px)
8. Height (px)
*/

@mixin textGlitch($name, $intensity, $textColor, $background, $highlightColor1, $highlightColor2, $width, $height) {

color: $textColor;
position: relative;
$steps: $intensity;

// Ensure the @keyframes are generated at the root level
@at-root {
// We need two different ones
@for $i from 1 through 2 {
@keyframes #{$name}-anim-#{$i} {
@for $i from 0 through $steps {
#{percentage($i*(1/$steps))} {
clip: rect(
random($height)+px,
$width+px,
random($height)+px,
0
);
}
}
}
}
}
&:before,
&:after {
content: attr(data-text);
position: absolute;
top: 0;
left: 0;
width: 100%;
background: $background;
clip: rect(0, 0, 0, 0);
}
&:after {
left: 2px;
text-shadow: -1px 0 $highlightColor1;
animation: #{$name}-anim-1 2s infinite linear alternate-reverse;
}
&:before {
left: -2px;
text-shadow: 2px 0 $highlightColor2;
animation: #{$name}-anim-2 3s infinite linear alternate-reverse;
}

}

There are a million different ways to approach it, this is just one. Totally depends on how much you want the mixin to do for you, how much customizability you want or need, what you want left in the HTML, etc.


I also made two more mixins, one for applying this effect to images, and on for inline SVG. They are different, because they don't use pseudo elements to make the copies, coloring happens in different ways, positioning happens differently, etc. Here's all three of them together.


And a demo:


See the Pen CSS Glitched Text by Chris Coyier (@chriscoyier) on CodePen.




Glitch Effect on Text / Images / SVG is a post from CSS-Tricks








Donnerstag, 4. September 2014

Sponsor: Frontend Masters – Expert Web Development Training




CSS-Tricks





Sponsor: Frontend Masters – Expert Web Development Training



Frontend Masters produces quality video training by industry leaders like Kyle Simpson, Douglas Crockford and Estelle Weyl. I like how these courses are targeted at intermediate and advanced developers:


You've got the basics down and don't want to learn from teachers who just spoon feed you their google results - you want to learn from the masters! Here, you get experts as teachers - people who are actively shaping the industry


Upgrade your JavaScript, CSS and front-end skills with Frontend Masters courses. Check out the complete course list.


Direct Link to ArticlePermalink



Sponsor: Frontend Masters – Expert Web Development Training is a post from CSS-Tricks








Mittwoch, 3. September 2014

New Poll: What one specific skill set are you most jealous of?




CSS-Tricks





New Poll: What one specific skill set are you most jealous of?



Rather than ask you what you are already good at, I thought it would be interesting to ask you what do you wish you were good at.


I just picked ten skill sets that all have to do with the web/tech world:




  • Management

  • Marketing

  • Knowing / Practicing the Law

  • Back End Development

  • Front End Development

  • Video / Audio Production

  • Database Administration

  • Server Management

  • Writing / Copywriting

  • Visual / Interaction Design


If you had to just pick one of those that you most wish you were good at (and aren't now), what would it be? Which are you the most jealous of?


Vote in the poll widget in the sidebar (large screen) or further down the ol' tube (small screen).


If you have one that isn't on the list, feel free to share in the comments. But in the interest of a fair data set, we'll leave the poll how it is.




New Poll: What one specific skill set are you most jealous of? is a post from CSS-Tricks