Foreword for CSS In Depth

Keith Grant recently released a brand new book on CSS: CSS in Depth. If you’re looking for a book focused specifically on learning CSS, you’ve found it. I was happy to write the foreword for it, which I’ll republish here.


“A minute to learn… A lifetime to master.” That phrase might feel a little trite these days, but I still like it. It was popularized in modern times by being the tagline for the board game Othello. In Othello, players take turns placing white or black pieces onto a grid. If, for example, a white piece is played trapping a row of black pieces between two white, all the black pieces are flipped and the row becomes entirely white.

Like Othello, it isn’t particularly hard to learn the rules of CSS. You write a selector that attempts to match elements, then you write key/value pairs that style those elements. Even folks just starting out don’t have much trouble figuring out that basic syntax. The trick to getting good at CSS, as in Othello, is knowing exactly when to do what.

CSS is one of the languages of the web, but it isn’t quite in the same wheelhouse as programming. CSS has little in the way of logic and loops. Math is limited to a single function. Only recently have variables become a possibility. Rarely do you need to consider security. CSS is closer to painting than Python. You’re free to do what you like with CSS. It won’t spit out any errors at you or fail to compile.

The journey to getting good at CSS involves learning everything CSS is capable of. The more you know, the more natural it starts to feel. The more you practice, the more easily your brain will reach for that perfect layout and spacing method. The more you read, the more confident you’ll feel in tackling any design.

Really good CSS devs aren’t deterred by any design. Every job becomes an opportunity to get clever, a puzzle to be solved. Really good CSS devs have that full and wide spectrum of knowledge of what CSS is capable of. This book you have is part of your journey to being that really good CSS dev. You’ll gain that spectrum of knowledge necessary to getting there.

If you’ll permit one more metaphor, despite CSS going on a couple of decades old, it’s a bit like the wild wild west. You can do just about whatever you want to do, as long as it’s doing what you want. There aren’t any hard and fast rules. But because you’re all on your own, with no great metrics to tell you if you’re doing a good job or not, you’ll need to be extra careful. Tiny changes can have huge effects. A stylesheet can grow and grow and become unwieldy. You can start to get scared of your own styles!

Keith covers a lot of ground in the book, and every bit of it will help you become a better CSS developer and tame this wild wild west. You’ll deep dive into the language itself, learning what CSS is capable of. Then, just as importantly, you’ll learn about ideas around the language that level you up in other ways. You’ll be better at writing code that lasts, is understandable, and performant.

Even seasoned devs will firm up their skills here. If you find yourself reading about something that you already know, you’ll firm up your skills, affirm your knowledge, and find little “oooo” bits that surprise you and extend that base.


Here’s that link to buy it again.

The post Foreword for CSS In Depth appeared first on CSS-Tricks.

Custom List Number Styling

How about a classic CSS trick! This isn’t even so tricky anymore, since CSS has counter-increment and counter-reset and such that is perfect for this. I just wanted to make sure you knew how it works and had some easy-to-copy examples at the ready.

Let’s say all you wanna do is style the dang numbers:

See the Pen Custom List Style 2 by Chris Coyier (@chriscoyier) on CodePen.

Here’s an example from the CodePen Challenges pages:

See the Pen Custom List Counters by Chris Coyier (@chriscoyier) on CodePen.

The keyframers made a Pen the other day that used pretty cool styles. Here’s a redux:

See the Pen Custom List Style 3 by Chris Coyier (@chriscoyier) on CodePen.

Recipe sites are great places to look for custom list styles, as lists of steps are such a prevelant feature. On Mat Marquis’ site, he’s got some fun ones. I ripped off his CSS and moved it here:

See the Pen Wilto Counters by Chris Coyier (@chriscoyier) on CodePen.

Make sure to check out the fun little media query change. Lea Verou’s food site, of course, has counter-based numbering as well.

Here’s an interesting demo from Jonathan Snook that has a “timeline” look and uses custom counters to label each section:

See the Pen Timeline CSS with Counters by Jonathan Snook (@snookca) on CodePen.

More Information

  • Counting With CSS Counters and CSS Grid
  • Numbering In Style
  • Fun Times with CSS Counters
  • Style List Markers in CSS
  • counter-increment and counter-reset in the Almanac, and the theoretical ::marker
  • Automatic Numbering With CSS Counters
  • Ordered Lists with Unicode Symbols

The post Custom List Number Styling appeared first on CSS-Tricks.

How React Reconciliation Works

React is fast! Some of that speed comes from updating only the parts of the DOM that need it. Less for you to worry about and a speed gain to boot. As long as you understand the workings of setState(), you should be good to go. However, it’s also important to familiarize yourself with how this amazing library updates the DOM of your application. Knowing this will be instrumental in your work as a React developer.

The DOM?

The browser builds the DOM by parsing the code you write, it does this before it renders the page. The DOM represents documents in the page as nodes and objects, providing an interface so that programming languages can plug in and manipulate the DOM. The problem with the DOM is that it is not optimized for dynamic state changes, React has to calculate if it is necessary to update the DOM. It does this by creating a virtual DOM and comparing it with the current DOM. In this context, the virtual DOM will contain the new state of the component.

Let’s build a simple component that adds two numbers. The numbers will be entered in an input field.

See the Pen reconciliation Pen by Kingsley Silas Chijioke (@kinsomicrote) on CodePen.

First, we’ll need to set up the initial state for the fields, then update the state when a number is entered. The component will look like this:

class App extends React.Component { state = { result: '', entry1: '', entry2: '' } handleEntry1 = (event) => { this.setState({entry1: event.target.value}) } handleEntry2 = (event) => { this.setState({entry2: event.target.value}) } handleAddition = (event) => { const firstInt = parseInt(this.state.entry1) const secondInt = parseInt(this.state.entry2) this.setState({result: firstInt + secondInt }) } render() { const { entry1, entry2, result } = this.state return( <div> <div> <p>Entry 1: { entry1 }</p> <p>Entry 2: { entry2 }</p> <p>Result: { result }</p> </div> <br /> <div> Entry 1:  <input type='text' onChange={this.handleEntry1} /> </div> <br /> <div> Entry 2:  <input type='text' onChange={this.handleEntry2} /> </div> <div> <button onClick={this.handleAddition} type='submit'>Add</button> </div> </div> ) }
}

On initial render, the DOM tree will look like this;

A screenshot from DevTools that shows the HTML rendering of the app.

When an entry is made in the first input field, React creates a new tree. The new tree which is the virtual DOM will contain the new state for entry1. Then, React compares the virtual DOM with the old DOM and, from the comparison, it figures out the difference between both DOMs and makes an update to only the part that is different. A new tree is created each time the state of App component changes — when a value is entered in either of the inputs field, or when the button is clicked.

Animated gif showing how the markup in DevTools changes when numbers are added to the input field.

Diffing Different Elements

When the state of a component changes so that an element needs to be changed from one type to another, React unmounts the whole tree and builds a new one from scratch. This causes every node in that tree to be destroyed.

Let’s see an example:

class App extends React.Component { state = { change: true } handleChange = (event) => { this.setState({change: !this.state.change}) } render() { const { change } = this.state return( <div> <div> <button onClick={this.handleChange}>Change</button> </div> { change ? <div> This is div cause it's true <h2>This is a h2 element in the div</h2> </div> : <p> This is a p element cause it's false <br /> This is another paragraph in the false paragraph </p> } </div> ) }
}

On initial render, you will see the div and its contents and how clicking the button causes React to destroy the div’s tree with its content and build a tree for the <p> element instead. Same happens if we have the same component in both cases. The component will be destroyed alongside the previous tree it belonged to, and a new instance will be built. See the demo below;

See the Pen reconciliation-2 Pen by Kingsley Silas Chijioke (@kinsomicrote) on CodePen.

Diffing Lists

React uses keys to keep track of items in a list. The keys help it figure out the position of the item on a list. What happens when a list does not have keys? React will mutate every child of the list even if there are no new changes.

In other words, React changes every item in a list that does not have keys.

Here’s an example:

const firstArr = ['codepen', 'codesandbox']
const secondArr = ['github', 'codepen', 'bitbucket', 'codesanbox'] class App extends React.Component { state = { change: true } handleChange = (event) => { this.setState({change: !this.state.change}) } render() { const { change } = this.state return( <div> <div> <button onClick={this.handleChange}>Change</button> </div> <ul> { change ? firstArr.map((e) => <li>{e}</li>) : secondArr.map((e) => <li>{e}</li>) } </ul> </div> ) }
}

Here, we have two arrays that get rendered depending on the state of the component. React has no way of keep track of the items on the list, so it is bound to change the whole list each time there is a need to re-render. This results in performance issues.

In your console, you will see a warning like this:

Warning: Each child in an array or iterator should have a unique "key" prop.

To fix this, you add a unique key for each item on the list.

const firstArr = ['codepen', 'codesandbox']
const secondArr = ['github', 'codepen', 'bitbucket', 'codesanbox'] class App extends React.Component { state = { change: true } handleChange = (event) => { this.setState({change: !this.state.change}) } render() { const { change } = this.state return( <div> <div> <button onClick={this.handleChange}>Change</button> </div> <ul> { change ? firstArr.map((e, index) => <li key={e.index}>{e}</li>) : secondArr.map((e, index) => <li key={e.index}>{e}</li>) } </ul> </div> ) }
}

See the Pen reconciliation-3 Pen by Kingsley Silas Chijioke (@kinsomicrote) on CodePen.

Wrapping Up

In summary, here are the two big takeaways for understanding how the concept of reconciliation works in React:

  • React can make your reconciliation process.
  • React doesn’t do a full rerender of your DOM nodes. It only changes what it needs to. The diffing process is so fast that you might not notice it.

The post How React Reconciliation Works appeared first on CSS-Tricks.

The backdrop-filter CSS property

I had never heard of the backdrop-filter property until yesterday, but after a couple of hours messing around with it I’m positive that it’s nothing more than magic. This is because it adds filters (like changing the hue, contrast or blur) of the background of an element without changing the text or other elements inside.

Take this example where I’ve replicated the iOS notification style: see how the background of each of these boxes are blurred but the text isn’t?

That’s only a single line of CSS to create that faded background effect, just like this:

.notification { backdrop-filter: blur(3px);
}

Now it’s worth noting that browser support for this CSS property isn’t particularly well supported just yet (see below). But we’ve been trying to do this sort of filtering stuff for a really long time and so it’s great to see that progress is being made here. Chris wrote about the “frosted-glass” technique in 2014 and way back then you had to use a bunch of weird hacks and extra images to replicate the effect. Now we can write a lot less code to get the same effect!

We also get to pick from a lot more filters than just that frosted glass style. The following demo showcases all of the backdrop-filter values and how they change the background:

Each of these boxes are just separate divs where I’ve applied a different backdrop-filter to each. And that’s it! I sort of can’t believe how simple this is, actually.

Of course you can chain them together like so:

.element { backdrop-filter: blur(5px) contrast(.8);
} 

And this could make all sorts of elaborate and complex designs, especially if you start combining them together with animations.

But wait, why do we even need this property? Well, after reading up a little it seems that the go-to default example is a modal of some description. That’s what Guillermo Esteves was experimenting with back in 2015:

See the Pen PwRPZa by Guillermo Esteves (@gesteves) on CodePen.

I reckon we can do something much weirder and more beautiful if we put our minds to it.

A note about browser support

The backdrop-filter property is not well supported at the time of this writing. And even in Safari where it is supported, you’ll still need to prefix it. There’s no support for Firefox at all. But, really, do websites need to look exactly the same in every browser?

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

Chrome Opera Firefox IE Edge Safari
No No No No 17 9*

Mobile / Tablet

iOS Safari Opera Mobile Opera Mini Android Android Chrome Android Firefox
9.0-9.2* No No No No No

Further reading

  • backdrop-filter on MDN
  • Building iOS-like transparency effects in CSS with backdrop-filter

The post The backdrop-filter CSS property appeared first on CSS-Tricks.

How to build a slide deck in PowerPoint that isn’t god awful

“Oooh! A PowerPoint Presentation!”

— No one ever

Nobody likes a slide show. I don’t even have to back that assertion up with evidence. It’s a universal truth — like saying “the sky is blue”, “the grass is green” or “The Mummy with Tom Cruise is the worst movie ever made.” And if you haven’t seen The Mummy reboot, I just saved you and you should be grateful.

It’s as if there is some unwritten rule that says: if you do a PowerPoint presentation, it has to be measurably boring on a physical level.

It doesn’t have to be this way. We can make engaging and (I hate this word but watch me use it anyway) delightful slide shows and you only need to know two things:

  1. How to work with shapes
  2. The “Morph” transition

Here is an example of the slideshow we’re going to be building in this post. Almost all of this will be handcrafted — including most of the artwork. I think you’ll be surprised at how easy it is to do. Let’s just say it’s about 1,000 times easier than sitting through “The Mummy 2017.”

To get started, you need to first pick a template by not picking a template.

Pick a template and then don’t pick a template

One thing that most people struggle with is just deciding on a template to use. You don’t need a template, but you do need some creative inspiration. You can just look on the main PowerPoint template gallery for ideas. For the city theme, I took inspiration from this template.

Keep in mind that your template doesn’t have to be related to your content. If you juxtapose something like a spring time city theme with a concept like Serverless, it provides an upbeat and friendly backdrop on which to talk about a concept that might otherwise be intimidating.

Just looking through this template gallery, you can take inspiration from the “Drops” template to build an underwater theme, the “Parcel” template to build a package theme — maybe a pile of packages on a table that you can move through. I don’t know. I can’t come up with all the ideas here.

Now that you have inspiration, the next step is to copy a great artist.

Great artists steal

Steve jobs famously quoted Picasso by saying, “Great artists steal” and then didn’t give him the credit, which is the pinnacle of irony.

That quote is not entirely true. You can borrow ideas and even form, but if you borrow too much, you are just ripping it off. It’s a fine line. But this is a PowerPoint presentation. Not an iPhone. It’s not like anybody but the eight people in your talk are going to see this.

For the city, we can just Google and see what other people are doing. I usually Google and then put “png” along with the search result because I want a cartoon city. The PNG image format is used for pictures that have only a few colors, and those are usually cartoons and logos. What we’re looking for here is something that is as “flat design” as possible.

This one is perfect. Flat design is the best thing to ever happen to non-designers. You used to have to actually be able to draw things and make them look realistic and all 3-D and stuff. Thanks to Flat Design, you slap a white square on a page with a heart in the corner and call it an icon. Thanks, Flat Design!

It is super easy to replicate or build your own flat artwork with some simple shapes in PowerPoint, which is exactly what we’re going to do.

Building the city with shapes

We’re going to replicate that city PNG image from our Google image search with nothing but shapes and our own Steve Jobs drive to steal art. For starters, just set the background of the slide to a light blueish green. We use a linear gradient turned 90° so that it becomes vertical, putting the white at the bottom so it looks more like light is coming from behind the buildings.

Our first building is just a rounded rectangle from the “Insert Shape” menu. We can let it sit just off the edge of the slide instead of having to get the bottom perfect. This is our first building so it’s also slightly off the screen to the left.

Most of our buildings are the same basic shape. We can copy this one, resize it and change the colors to get more buildings. I heavily “borrow” colors from my image inspiration. Having a great color palette will make all of the difference in the end.

OK! Now let’s add in some simple rectangle buildings. You may have to right-click and adjust the z-index ordering of the buildings selecting “Send To Back / Send Backward.”

Our last building has a little spire on top. This is creating by adding a rounded rectangle for the building, one for the top and the one for the spire. You can adjust how rounded they are by dragging the little yellow square. I have split them out here so you can see what each looks like.

Then just put the shapes together. This is like LEGO only it didn’t cost you $180 bucks.

Beautiful! Now let’s add some windows to these buildings. Guess what you make windows out of? That’s right — more rounded rectangles.

Add in a small black rounded rectangle the runs the length of the first building. Then just copy and paste them down until you have a whole building’s worth.

Now the windows look a little wonky because they are not perfectly aligned. There are a few ways to fix this. You can zoom in using the little zoom slider in the bottom of the window. You can also select all the windows and then right-click and select “size and position.” This opens up the sidebar and you can set the horizontal position “from” to 0. This will pull them a bit off the building so just adjust until they are centered.

Now repeat this for each building, using the original image for inspiration. Look at how they are doing windows. Some are long, some are square and some are in groups.

When you are done, you will have buildings with windows and guess what — they actually look like buildings!

Let’s add some hills and trees. These are just shapes too. The hills are stretched out green ovals. The trees are thick lines with green circles on top. Remember, people are expecting a PowerPoint presentation here, so the bar is already pretty low.

We need a few clouds. For that, we’re going to use the thenounproject.com. You don’t have to use Noun Project, but I find that a subscription is well worth all of the icons that I get. But you could very well just Google “cloud png.”

The other cool thing about Noun Project is that you can get your icons in different colors. Now that we have clouds, we just insert a few and adjust their size.

What if all of our slide text looks like it was written in clouds? For this slide, the sky is all we have to work with, so a cloud font would work perfectly. There are a lot of font sites out there, and I ended up using one called “JFRockSolid.” It’s supposed to be rocks, but when you make it white it looks like clouds. At least it looks like clouds to me.

Well, now that I’ve typed it out, it looks like rocks. DAMMIT.

We’re getting so close to being done! Let’s add in one more thing — a plane towing a banner with our subtitle on it.

For the plane, I just googled for “cartoon plane png.” I wanted something with a few more colors and details. Sometimes we can build these things, sometimes we can use the Noun Project, and sometimes we just straight up rip off images from Google. Again, this is a technical presentation, not a customer-facing product. It’s also nice to include a slide at the end which gives credit for all the images you used. Be nice.

I just resized the plane and flipped it horizontally. Note that in order to flip images horizontally in PowerPoint, you have to use the 3-D Rotation on the x-axis. I know, so intuitive.

For the banner the plane is towing, we can use the “wave” shape.

Now, how do we add some text to this wave shape so that the text follows the ripple of the shape? This is a banner being buffeted by the wind, so our text would look silly if it’s just flat on the banner. Don’t believe me?

I told you. So, how do we do this? Well, for the first time your life, the answer is “Word Art.”

Word Art acts like a shape, so we can skew it. I just add the first Word Art type and then remove the shadow and change the color. Then, under “Text Effects” you are going to select “ABC Transform.” Then look for the shape that most closely resembles the one you want to align to. In our case, the shape is “wave 1.”

Now just adjust your text shape using the little drag handles until it looks good on the banner. Change the font if that feels right. I’m using “Bernard MT”. It’s not perfect, but it’s a huge improvement.

Connect the plane to the banner with a “curve” shape.

You’ll need to click to start the line and then click everywhere along the path between the plane and the banner where you want a curve. To end the line, hit the “escape” key. You’ll screw it up the first time, then you’ll get it.

And with that, we have wrapped up our first slide and done most of the hard work. It looks goofy in the presentation space, but here is what it will look like when you actually start the show.

“Burke — this does not look anything like a proper PowerPoint presentation.”

Thank you. Thank you very much.

We’re now ready to begin building our show by zooming in and out of the city. The only transition we are going to use is going to be “Morph.”

Using the Morph transition

The Morph transition animates objects to a new location or size. The key is to make sure you have the same objects between slides. Morph needs a reference to the element to be animated so it has to be an exact duplicate.

Morph is a cool name. I’m going to name my next kid Morph. Morph Holland. Yikes. That looks way worse on paper than it sounded in my head.

Duplication is the name of the game here. Duplicate the first slide by right-clicking and selecting “Duplicate slide.”

Now we’re just going to play a game of moving things around and making them either bigger or smaller. And because most of our images are just shapes, we can resize them without degrading image quality.

The easiest way to move all these shapes is to group them into the left and right side by selecting several images and then right-click and select “group.” Here is how I have mine grouped…

Make the following moves….

  1. Move the left group of buildings and hills almost all the way off the slide.
  2. Move the plane and banner group off to the slide to the right.
  3. Move the existing title off the top of the slide
  4. Copy the title and then move the copy back onto the slide and change the text

You slide should look something like this…

Now copy the new title text “Main Point I Want To Make” and paste it on the first slide. Then move it down to the bottom of the slide. Your first slide will now look like this…

On the second slide and select the “Transitions” tab and use the “Morph transition. Watch the magic unfold!

You can experiment with zooming in on any of the elements and then using that element as the slide background. For instance, maybe you have an image of an adorable pug that you want to show. You can animate individual elements with standard animations.

The rest is up to you. You can zoom in on buildings and use the windows for bullet points. Create a billboard and use that on the slide. I added a school bus (which I made with shapes BTW) just because school buses are awesome. I can say that now because I don’t have to ride one anymore. My kids would probably take serious issue with this.

Make something cool — because you can

Just like that you can create PowerPoint presentations that are so much fun to watch. People will wonder what the heck the slide is going to do next. They’ll stick around just for that. It does take some extra time to put together a high quality presentation, but on behalf of everyone who has ever sat through a PowerPoint presentation, I would like to thank you in advance.

If you would like to just grab and use this presentation (feel free to do so), you can download it here.

The post How to build a slide deck in PowerPoint that isn’t god awful appeared first on CSS-Tricks.

Where Lines Break is Complicated. Here’s all the Related CSS and HTML.

Say you have a really long word within some text inside an element that isn’t wide enough to hold it. A common cause of that is a long URL finding it’s way into copy. What happens? It depends on the CSS. How that CSS is controlling the layout and what the CSS is telling the text to do.

This is what a break-out text situation might be like:

The text hanging out of the box is a visual problem.

One possibility is overflow: hidden; which is a bit of a blunt force weapon that will stop the text (or anything else) from hanging out. Yet, it renders the text a bit inaccessible. In some desktop browsers with a mouse, you might be able to triple-click the line to select the URL and copy it, but you can’t count on everyone knowing that or that it’s possible in all scenarios.

Overflow is the right word here as well, as that’s exactly what is happening. We have overflow: auto; at our disposal as well, which would trigger a horizontal scrollbar. Maybe suitable sometimes, but I imagine we’ll all agree that’s not generally an acceptable solution.

What we want is the dang long URL (or text of any kind) to break to the next line. There are options! Let’s start with a place to attempt figure this stuff out.

Experimental Playground

My idea here is to have a resizeable panel of content combined with a variety of CSS property/values that you can toggle on and off to see the effects on the content.

This isn’t comprehensive or perfectly executed, I’m sure. It’s just some of the properties I’m aware of.

See the Pen Figuring Out Line Wrapping by Chris Coyier (@chriscoyier) on CodePen.

The Sledgehammer: `word-break: break-all;`

Allows words to be broken anywhere. The word-break property does “solve” the issue:

p { word-break: break-all;
}

In an email exchange with fantasi, she explained that this works because the word-break property redefines what a word is. The break-all value essentially treats non-hyphens property does what you might expect…allows for hyphenation in line breaks. Hyphens can sometimes do the trick in URLs and long words, but it’s not guaranteed. A long number would trip it up, for example. Plus, hyphens affect all the text, breaking words more liberally to help text hug that right edge evenly.

p { hyphens: auto;
}

fantasai told me:

“If a ‘word’ straddles the end of the line, we can hyphenate it.”

I guess “word” helps put a finger on the issue there. Some problematically long strings aren’t “words” so it can’t be counted on to solve all overflow issues.

Future Sledgehammer: `line-break: anywhere;`

There is a property called line-break. It’s mostly for punctuation, apparently, but I can’t seem to see it working in any browser. fantasai tells me there will be a new value called anywhere which is:

“like word-break: break-all; except it actually breaks everything like a dumb terminal client”

.

Other HTML Stuff

  • The <br> element will break a line wherever it renders. Unless it’s display: none;!
  • The <wbr> element is a “word break opportunity” meaning a long word that would normally cause an annoying overflow issue could be told that it’s ok to break at a certain point. Useful! It behaves like a zero-width space.

Other CSS Stuff

  • The &shy; character is just like the <wbr> element.
  • You can inject a line break via psuedo elmement like ::before { content: "\A"; } as long as elment isn’t inline (or if it is, it needs white-space: pre;)

The post Where Lines Break is Complicated. Here’s all the Related CSS and HTML. appeared first on CSS-Tricks.

Overriding Default Button Styles

There are a variety of “buttons” in HTML. You’ve got:

<button>Button</button>
<input type="button" value="Button">

Plus, for better or worse, people like having links that are styled to match the look of other true buttons on the site

<a href="#0" class="button">Button</a>

One challenge is getting all those elements to look and layout exactly the same. We’ll cover that a few ways.

Another challenge is getting people to use them correctly

This is a bit surprising to me — but I hear it often enough to worry about it — is that more and more developers are using <div>s for buttons. As in, they just reach for whatever generic, styling-free HTML is handy and build it up as needed. Andy Bell explains why a real button is better:

So, <button> elements are a pain in the butt to style right? That doesn’t mean you should attach your JavaScript events to a <div> or an <a href="#"> though. You see, when you use a <button>, you get keyboard events for free. You’re also helping screen reader users out because it’ll announce the element correctly.

And here’s Andy again helping you out with a chunk of CSS that’ll get you a cleanly styled button:

See the Pen Button Pal — some basic button styles by Andy Bell (@hankchizljaw) on CodePen.

It’s that styling that just might be the mental roadblock

It’s a bit understandable. Buttons are weird! They have a good amount of default styling (that come from the “User Agent Stylesheet”) that varies from browser to browser and means you have work to do to get them exactly how you want.

See all the weirdness there?

  • Without any styling, the button is kinda little and has that native border/border-radius/box-shadow thing going on.
  • Just by setting the font-size, we lose all those defaults, but it’s got a new default look, one with a border and square corners, a gradient background, and no box-shadow. This is essentially -webkit-appearance: button;.
  • Buttons have their own font-family, so don’t inherit from the cascade unless you tell it to.

Here’s Chrome’s user agent stylesheet for buttons:

Firefox behaves a bit differently. See in the video above how setting border: 0; removed the border in Chrome, but also the background? Not the case in Firefox:

I only point this out to say, I get it, buttons are truly weird things in browsers. Factor in a dozen other browsers, mobile, and the idea that we want to style all those different elements to look exactly the same (see the opening of the article), and I have a modicum of empathy for people wanting to avoid this.

Never hurts to consult Normalize

Normalize does a good amount:

/** * 1. Change the font styles in all browsers. * 2. Remove the margin in Firefox and Safari. */ button,
input,
optgroup,
select,
textarea { font-family: inherit; /* 1 */ font-size: 100%; /* 1 */ line-height: 1.15; /* 1 */ margin: 0; /* 2 */
} /** * Show the overflow in IE. * 1. Show the overflow in Edge. */ button,
input { /* 1 */ overflow: visible;
} /** * Remove the inheritance of text transform in Edge, Firefox, and IE. * 1. Remove the inheritance of text transform in Firefox. */ button,
select { /* 1 */ text-transform: none;
} /** * Correct the inability to style clickable types in iOS and Safari. */ button,
[type="button"],
[type="reset"],
[type="submit"] { -webkit-appearance: button;
}

I was a tiny bit surprised to see WTF, Forms? not cover buttons, only because of how much weirdness there is. But the form elements that project whips into shape are even more notoriously difficult!

A Style-Testing Kinda Thingy

I feel like the answer to this is basically a big ol’ block of CSS. That’s what Andy provided, and you could very likely come to one on your own by just being a little heavier handed than the usual of setting style rules with your buttons.

Still, I felt compelled to make a little tester machine thingy so you can toggle styles on and off and see how they all go together in whatever browser you happen to be in:

See the Pen Consistent button styles by Chris Coyier (@chriscoyier) on CodePen.

A11y

The biggest point here is to use the correct native elements, as you get a bunch of functionality and accessibility for free. But you might as well get the styling right, too!

While we’re talking buttons, I’m gonna use the same quote I used in our When To Use The Button Element post from MDN:

Warning: Be careful when marking up links with the button role. Buttons are expected to be triggered using the Space key, while links are expected to be triggered through the Enter key. In other words, when links are used to behave like buttons, adding role="button" alone is not sufficient. It will also be necessary to add a key event handler that listens for the Space key in order to be consistent with native buttons.

You don’t need role="button" on <button> because they are already buttons, but if you’re going to make any other element button-like, you have more work to do to mimic the functionality.

Plus, don’t forget about :hover and :focus styles! Once you’ve wrangled in the styles for the default state, this shouldn’t be so hard, but you definitely need them!

button:hover,
button:focus { background: #0053ba;
} button:focus { outline: 1px solid #fff; outline-offset: -4px;
} button:active { transform: scale(0.99);
}

The post Overriding Default Button Styles appeared first on CSS-Tricks.

Decorating lines of text with box-decoration-break

An institution’s motto, an artist’s intro, a company’s tagline, a community’s principle, a service’s greeting… all of them have one thing in common: they’re one brief paragraph displayed on a website’s home page — or at least the about page!

It’s rare that just one word or one line of text welcomes you to a website. So, let’s look at some interesting ways we could style the lines of a paragraph.

To see how things currently are, let’s try giving borders to all the lines of some text in an inline span and see how it looks:

<p><span>Hummingbirds are birds from...</span></p>
span { border: 2px solid;
}

See the Pen Broken inline box. by Preethi (@rpsthecoder) on CodePen.

The edges appear broken, which they technically are, as the inline box has been fragmented into multiple lines. But we can fix those broken edges with box-decoration-break!

The box-decoration-break property in CSS can decorate the edges of fragments of a broken inline box (as well as of a page, column, and region boxes).

Its value, clone, does that with the same design that appears in the box’s unbroken edges, and its default value, slice, does not copy the decorations at the edges, keeping the break very visible like you saw in the demo above.

Let’s try it:

span { border: 2px solid; box-decoration-break: clone;
}

See the Pen Broken inline box w/ box-decoration-break. by Preethi (@rpsthecoder) on CodePen.

The property affects not only the border but also the shadow, spacing, and background of the broken edges.

Let’s play with the background first. While writing the post on knockout text, I was working with the background-clip property and wanted to see if the design held up for multiple lines of text. It didn’t.

The background gradient I applied was not replicated in every line, and after clipping it, only the first one was left with a background. That is, unless box-decoration-break: clone is added:

<p><span>Singapore:<br>Lion City</span></p>
span { background-image: linear-gradient(135deg, yellow, violet); background-clip: text; color: transparent; padding: .5em; box-decoration-break: clone;
}

See the Pen Gradient multi-line text w/box-decoration-break. by Preethi (@rpsthecoder) on CodePen.

The background-clip property with the text value clips a background to the shape of its foreground text. Since we used box-decoration-break, the gradient background is shown and clipped uniformly across all the lines of the text.

Going back to the border, let’s see how its shape and shadow can be copied across the broken edges, along with padding:

<img src="tree.png">
<p><span>Supertrees are tree-like structures...</span></p>
<img src="tree.png">
<p><span>Supertrees are tree-like structures...</span></p>
span { background: rgb(230,157,231); border-radius: 50% 0%; box-shadow: 0 0 6px rgb(41,185,82), 0 0 3px beige inset; padding: .5em 1.3em; box-decoration-break: clone;
} p:nth-of-type(2) span { background-clip: content-box;
}

See the Pen Inline border shape & shadow w/box-decoration-break. by Preethi (@rpsthecoder) on CodePen.

In the second paragraph of the demo, the background is cropped until the content box (background-clip: content-box). As you can see, the crop happens in the broken edges as well, because of box-decoration-break: clone.

Another way we can style borders is with images. You might see a gradient border around the lines of text below, covering the broken edges, if the browser you’re now using supports border-image and the application of box-decoration-break over its result.

<p><span>The Malaysia–Singapore Second Link...</span></p>
span { border: 2px solid; border-image: linear-gradient(45deg, #eeb075, #2d4944) 1; background: #eef6f3; padding: .5em 1.3em; box-decoration-break: clone;
}

See the Pen Inline border image w/ box-decoration-break. by Preethi (@rpsthecoder) on CodePen.

An additional behavior we can tap into for decorating individual lines is of outline’s. In supported browsers, box-decoration-break can add an outline to every line of the text, including the broken edges, which is useful for creating bicolored dashed borders.

<p><span>Cloud Forest replicates...</span></p>
span { outline: 2px dashed rgb(216,255,248); box-shadow: 0 0 0 2px rgb(39,144,198); background: #fffede; padding: .5em 1.3em; animation: 1s animateBorder ease infinite; box-decoration-break: clone;
} @keyframes animateBorder{ to{ outline-color: rgb(39,144,198); box-shadow: 0 0 0 2px rgb(216,255,248); }
}

See the Pen Inline outline w/ box-decoration-break. by Preethi (@rpsthecoder) on CodePen.

As observed in the demo, box-decoration-break withstands animation.

Besides borders and backgrounds, box-decoration-break can also manage shapes applied over elements. There is not much use for it in inline boxes, and is maybe better used in a column or page box, although the application is not yet widely supported in browsers.

But to show an example of what that does, let’s try applying the clip-path property to the span.

The property clip-path itself is only fully supported by Firefox, so only in it you might see an expected outcome. But following are two images: the results of applying a circular clip path over the span, without and with box-decoration-break.

span { clip-path: circle(50% at 202.1165px 69.5px); ...
}
A screenshot of a span of text being highlighted in DevTools showing that text is split up in three lines and with uneven start and end points.
Circular clip-path on a span
span { clip-path: circle(50% at 202.1165px 69.5px); box-decoration-break: clone; ...
}
A screenshot of a span of text being highlighted in DevTools showing that text is split up in three lines and with even start points but uneven end points.
Circular clip-path on a span with box-decoration-break: clone

You’ll notice in the first image that the 50% radius value is derived from the width of the inline box (the longest line) where box-decoration-break is not used.

The second image shows how box-decoration-break: clone redefines the computed value for 50% by basing them on the widths of the individual lines while keeping the center same as before.

And here’s how the inset function of clip-path (an inset rectangle) applied over the span clips it without and with box-decoration-break:

span { clip-path: inset(0); ...
}
A screenshot of a span of text being highlighted in DevTools showing that text is all on one line but the span continues for three lines with even start points but uneven end points.
Inset clip-path on a span
span { clip-path: inset(0); box-decoration-break: clone; ...
}
Inset clip-path on a span with box-decoration-break: clone

Without box-decoration-break, only a portion of the first line that matches the length of the shortest is visible, and with box-decoration-break: clone, the first line is fully visible while the rest of the box is clipped.

So, maybe if you ever want to show only the first line and hide the rest, this can come in handy. But, as I mentioned before, this application is more suitable for other types of boxes than ones that are inline. Either way, I wanted to show you how it works.

Browser Support

As we’ve seen here, box-decoraton-break can be super useful and opens up a lot of possibilities, like creating neat text effects. The property enjoys a lot support with the -webkit prefix, but is still in Working Draft at the time of this writing and lacks any support in Internet Explorer and Edge. Here’s where you can vote for Edge support.

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

Chrome Opera Firefox IE Edge Safari
69* 11 32 No No TP*

Mobile / Tablet

iOS Safari Opera Mobile Opera Mini Android Android Chrome Android Firefox
11.3* 11 all 62* 66* 57

Wrapping Up

The box-decoration-break: clone copies any border, spatial, and background designs applied on a fragmented inline box’s unbroken edges to its broken ones. This creates an even design across all the lines of the text, decorating them uniformly and can be super useful for all those blurbs of text that we commonly use on websites.

The post Decorating lines of text with box-decoration-break appeared first on CSS-Tricks.

Microsites for Case Studies

A lot of y’all have personal sites. Personal sites with portfolios. Or you work for or own an agency where showing off the work you do is arguably even more important. Often the portfolio area of a site is the most fretted and hard to pull off. Do you link to the live projects? Screenshots? How many? How much do you say? How much of the process do people care about?

I’m afraid I don’t have all the answers for you. I don’t really do much freelance, work for an agency, or have a need to present work I’ve done in this way.

But! I tweeted this the other day:

I was out to lunch with Rob from Sparkbox recently. A few years back, we worked together on a redesign of CodePen, and a byproduct of that was a microsite about that process.

I remember working on that microsite. It wasn’t a burden, it was kinda fun. We built it as we went, when all that stuff was fresh in our minds. Now that site is kind of a monument to that project. Nobody needs to touch it. It doesn’t load some global stylesheet from a main website. It’s a sub-domained microsite. It’ll be useful as long as it’s useful. When it’s not anymore, stop linking to it.

I’ve also watched loads of people struggle with what to put in that portfolio and how to deal with case studies. I’ve watched it be a burden to people redesigning their site or building one for the first time. I’ve also looked at a lot of personal sites lately, and the default is certainly to work the portfolio into the site itself.

Maybe for some of you, making your case studies into these microsites will be a useful way to go!

The post Microsites for Case Studies appeared first on CSS-Tricks.

CSS Environment Variables

We were all introduced to the env() function in CSS when all that drama about “The Notch” and the iPhone X was going down. The way that Apple landed on helping us move content away from those “unsafe” areas was to provide us essentially hard-coded variables to use:

padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);

Uh ok! Weird! Now, nine months later, an “Unofficial Proposal Draft” for env() has landed. This is how specs work, as I understand it. Sometimes browser vendors push forward with stuff they need, and then it’s standardized. It’s not always waiting around for standards bodies to invent things and then browser vendors implementing those things.

Are environment variables something to get excited about? Heck yeah! In a sense, they are like a more-limited version of CSS Custom Properties, but that means they can be potentially used for more things.

Eric also points out some very awesome early thinking:

ISSUE 4 – Define the full set of places env() can be used.

  • Should be able to replace any subset of MQ syntax, for example.
  • Should be able to replace selectors, maybe?
  • Should it work on a rule level, so you can insert arbitrary stuff into a rule, like reusing a block of declarations?

Probably still changeable-with-JavaScript as well. I would think the main reason CSS Custom Properties don’t work with media queries and selectors and such is because they do work with the cascade, which opens up some very strange infinite loop logic where it makes sense CSS doesn’t want to tread.

If you’re into the PostCSS thing, there is a plugin! But I’d warn… the same issues that befall preprocessing CSS Custom Properties applies here (except the first one in that article).

The post CSS Environment Variables appeared first on CSS-Tricks.