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.

Build Nodejs APIs Using Serverless

Simona Cotin did a great talk at Microsoft Build about Serverless technologies, called “Build Node APIs Using Serverless.” In this talk, she addresses pretty much every major gotcha that you might run into while creating Serverless infrastructure for JavaScript applications. Some of the topics included, but are not limited to:

  • CORS
  • Local Debugging with VS Code
  • Installing npm packages
  • Configuring REST-like URLs
  • Saving environment variables

All in all, it’s one of the best talks on Serverless I’ve seen, and if you’re interested in this topic, then I highly suggest giving it a watch.

Direct Link to Article — Permalink

The post Build Nodejs APIs Using Serverless 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.

Responsive tables, revisited

Lea Verou with some extra super fancy CSS trickery. No way we could miss linking this one up!

One of the problems with responsive table solutions, at least the ones where you are using CSS to rejigger things, is that there is duplicated content somewhere. Either in CSS or HTML.

Lea finds two ways to prevent that. One of which uses text-shadow to “duplicate” a copy of the text and move it into place. Another uses the Firefox-only element() function.

Another thing to remember: if you’re forcing table elements to anything other than their natural display value (like block), make sure to use ARIA roles so they don’t lose their accessibility usefulness.

Direct Link to Article — Permalink

The post Responsive tables, revisited 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.

A Strategy Guide To CSS Custom Properties

CSS preprocessor variables and CSS custom properties (often referred to as “CSS variables”) can do some of the same things, but are not the same.

Practical advice from Mike Riethmuller:

If it is alright to use static variables inside components, when should we use custom properties? Converting existing preprocessor variables to custom properties usually makes little sense. After all, the reason for custom properties is completely different. Custom properties make sense when we have CSS properties that change relative to a condition in the DOM — especially a dynamic condition such as :focus, :hover, media queries or with JavaScript.

Direct Link to Article — Permalink

The post A Strategy Guide To CSS Custom Properties appeared first on CSS-Tricks.

designsystems.com

The team at Figma has created a new resource for “learning, creating and evangelizing design systems” called Design Systems that already has a good collection of interviews and articles by some folks thinking about these things.

I particularly liked Jeroen Ransijn’s post on how to convince your company it’s ready for a design system, where he writes:

Building a design system is not about reaching a single point in time. It’s an ongoing process of learning, building, evangelizing and driving adoption in your organization.

Design systems are a popular topic. Ethan Marcotte recently looked at instances where patterns get weird, Lucan Lemonnier shared a process for creating a consistent design system in Sketch, and Brad Frost debunked the perception that design systems are rigid. Seems like Figma’s new site will be a nice curated repository of this ongoing discussion.

Direct Link to Article — Permalink

The post designsystems.com 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.

Locate and identify website visitors by IP address

(This is a sponsored post.)

Big thanks to ipstack for sponsoring CSS-Tricks this week!

Have you ever had the need to know the general location of a visitor of your website? You can get that information, without having to explicitly ask for it, by the user’s IP address. You’re just going to need a API to give you that information, and that’s exactly what ipstack is.

Here’s me right now:

This works globally through an API that covers over 2 million unique locations in over 200,000 cities around the world, and it’s update dozens of times a day.

It’s a nice clean JSON API for all you front-end JavaScript folks! XML is there too, if you need it. You’re probably curious about all the data you can get, so let’s just take a look:

{ "ip": "134.201.250.155", "hostname": "134.201.250.155", "type": "ipv4", "continent_code": "NA", "continent_name": "North America", "country_code": "US", "country_name": "United States", "region_code": "CA", "region_name": "California", "city": "Los Angeles", "zip": "90013", "latitude": 34.0453, "longitude": -118.2413, "location": { "geoname_id": 5368361, "capital": "Washington D.C.", "languages": [ { "code": "en", "name": "English", "native": "English" } ], "country_flag": "https://assets.ipstack.com/images/assets/flags_svg/us.svg", "country_flag_emoji": "&#x1f1fa;&#x1f1f8;", "country_flag_emoji_unicode": "U+1F1FA U+1F1F8", "calling_code": "1", "is_eu": false }, "time_zone": { "id": "America/Los_Angeles", "current_time": "2018-03-29T07:35:08-07:00", "gmt_offset": -25200, "code": "PDT", "is_daylight_saving": true }, "currency": { "code": "USD", "name": "US Dollar", "plural": "US dollars", "symbol": "$", "symbol_native": "$" }, "connection": { "asn": 25876, "isp": "Los Angeles Department of Water & Power" } "security": { "is_proxy": false, "proxy_type": null, "is_crawler": false, "crawler_name": null, "crawler_type": null, "is_tor": false, "threat_level": "low", "threat_types": null }
}

What is this useful for?

All kinds of things! Whatever you want! But here’s some very practical ones:

  • Does your site display times? You can adjust those times to the user’s local time zone, so long as you know where they are.
  • Does your site display currency? You can adjust your prices to show local currencies, so long as you know where they are.
  • Does your site only work in certain countries due to laws, regulations, or other reasons? You might want to deliver different experiences to those different countries. ipstack is also often used for protection against potential security threats.

Lots of big companies like Microsoft, Airbnb, and Samsung use ipstack.

Usage

ipstack has a free tier covering up to 10,000 requests over a month, and plans start at a reasonable $9.99 a month covering 5 times that many requests and unlocking useful modules like the Time Zone and Currency modules. Plans scale up to any level, including millions of requests a day.

Direct Link to Article — Permalink

The post Locate and identify website visitors by IP address 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.