Disable built-in dragging of text and images

Most browsers have built-in drag and drop support for different page elements like text and images. While this may be useful in most situations, it may become annoying in others. If you e.g. want to allow the user to scroll/move horizontally within a container by grabbing an item and moving the mouse, you will notice that nothing will move and you'll instead start dragging that element.

To disable this, add the following CSS to your content:

-webkit-user-drag: none
user-drag: none

-webkit-user-drag is only fully supported in ...

Unobtrusive JavaScript helper to progressively enhance HTML

The attached compiler() function below applies JavaScript behavior to matching HTML elements as they enter the DOM.

This works like an Unpoly compiler for apps that don't use Unpoly, Custom Elements or any other mechanism that pairs JavaScript with HTML elements.

The compiler() function is also a lightweight replacement for our legacy [$.unobtrusive()](https://makandracards.com/makandra/4-unobtrusiv...

Triggering JavaScript when an element is clicked

Often people need links which are not linked directly, but should trigger execution of JavaScript.

❌ Bad workarounds

You can find a lot of workarounds for that:

  • <a href="#">Do something with js!</a>
    This defines an empty anchor. This may lead the browser to let the page jump to the top when the link is clicked, unless you call preventDefault on the event. This is probably not what you want.

  • <a href="#!">Do something with js!</a>
    This tells the browser to jump to an anchor !. It depends on the browser implementation wha...

CSS has a built-in clearfix

The need for clearfix hacks has been greatly reduced since we could layout with Flexbox or CSS Grid.

However, when you do need a clearfix, there's no reason to use a hack anymore. You can just give the clearing container display: flow-root.

This is supported by all browsers except IE11.

CSS: How to force background images to scale to the container, ignoring aspect ratio

You can scale background images in CSS to the container size using background-size (Demo).

Commonly, we use contain or cover because we want to preserve the image's aspect ratio.
If you do not want to do that, simply provide scaling values for X and Y:

background-size: 100% 100%

(a simple 100% would mean 100% auto and respect the image's aspect ratio)

SVGs with a viewBox will force their aspect ratio

The above may not work for you when ...

Setting SASS variables as value for CSS custom properties

When using custom properties in your stylesheets, you may want to set a specific property value to an existing variable in your SASS environment. A pratical example would be a list of color variables that you've defined in colors.sass and that you would like to refer to in your stylesheets. However, simply assigning a variable will not work:

$my-great-blue: blue

:root
  --my-color: $my-great-blue

.sky
  background-color: var(--my-color)

The property value will not be valid and if you open the browser's inspection window, yo...

How to: Ensure proper iconfont rendering with Webpack

Background

After switching a project from Sprockets to Webpack, I started observing a bug that was hard to debug: Our custom icon font could sometimes not be displayed until a full page reload.

Digging deeper the only difference before and after the page load was the encoding interpretation of the iconfont stylesheet:

Correct representation (UTF-8):

.icon:before {
    content: ""
}

Broken representation (other charset):
`...

When does Webpacker compile?

Webpack builds can take a long time, so we only want to compile when needed.

This card shows what will cause Webpacker (the Rails/Webpack integration) to compile your assets.

When you run a dev server

While development it is recommended to boot a webpack dev server using bin/webpack-dev-server.

The dev server compiles once when booted. When you access your page on localhost before the initial compilation, the page may load without assets.

The ...

Ruby: How to convert hex color codes to rgb or rgba

When you have a hex color code, you can easily convert it into its RGB values using plain Ruby.

>> "#ff8000".match(/^#(..)(..)(..)$/).captures.map(&:hex)
=> [255, 128, 0]

You can use that to implement a simple "hex to CSS rgba value with given opacity" method:

def hex_color_to_rgba(hex, opacity)
  rgb = hex.match(/^#(..)(..)(..)$/).captures.map(&:hex)
  "rgba(#{rgb.join(", ")}, #{opacity})"
end
>> hex_color_to_rgba("#ff8000", 0.5)
=> "rgba(255, 128, 0, 0.5)"

If you need to support RGBA hex color codes,...

Capybara: Pretending to interact with the document

Browsers blocks abusable JavaScript API calls until the user has interacted with the document. Examples would be opening new tab or start playing video or audio.

E.g. if you attempt to call video.play() in a test, the call will reject with a message like this:

NotAllowedError: play() failed because the user didn't interact with the document first. https://goo.gl/xX8pDD

Workaround

To pretend document interaction in a test you can create an element, click on it, and remove the element again. This unblocks the entire JavaSc...

WYSIWYG with Action Text

Rails 6 includes a WYSIWYG editor, Action Text. It works out of the box quite well, but chances are that you want to add some custom functionality. This card contains some tips how to achieve this.

Setup

Basically, follow the guide in the Rails documentation. The automated script may not work with the way webpacker is configured in your project, but it should be easy to fix.

If you don't want the default c...

Rails: How to use custom flash types in controllers

Rails supports alert and notice as default flash types. This allows you to use these keys as options in e.g. redirect_to and as a helper in views e.g. <%= notice %> (instead of flash[:notice]).

class SomeController < ApplicationRecord
  def create
    @user = User.create!
    
    redirect_to user_path(@user), notice: "#{@user} created!" 
  end
end

In case you are using Bootstrap as CSS framework you might also want to support flashes like success. This can be done with the add_flash_types method.

class Applicat...

A few recent CSS properties

  • Feature Queries (Edge 12+): Similar to @media queries, @supports blocks can be scoped to browsers that support a given declaration. There is CSS.supports() to do the equivalent in Javascript.

  • backdrop-filter (Edge 17+, but not FF): Applying filters to what is visible through an element.

  • [touch-action](https://d...

Variable fonts for web developers

This card is mainly an explanation how variable fonts work in CSS, not necessarily a recommendation to actually use them.

What is a variable font?

Designing and rendering fonts are two highly complex topics. For an arbitrary text to appear properly on your screen, its font must be created multiple times for different "settings" like stroke width (boldness) and style (e.g. italic).

Now as web developers, we usually ship these variants of the same font via multiple @font-faces of the same font-family:

@font-face
  font-family...

CSS variables aka CSS Custom Properties

CSS variables are very different from preprocessor variables. While preprocessors use variables to compile a static piece of CSS, CSS custom properties are a reactive (i.e. live) part of the styles. Think of them like usual CSS properties that cascade, but have:

  • a special syntax: CSS variables always start with a double-dash (--color)
  • no inherent meaning: Defining a CSS variable will not change any styles in itself
  • a special functionality: CSS variables can be used within the values of other properties, including CSS variables...

BEM naming conventions

We structure our CSS using the BEM pattern.

Our naming convention for blocks, elements and modifiers has evolved over the years. This card shows our current style and various alternative styles that you might encounter in older projects.

The difference between the various styles are mostly a matter of taste and optics. I do recommend to not mix styles and be consistent within a given project.

Current convention

Our current BEM naming convention looks...

Vortrag: Content Security Policy: Eine Einführung

Grundidee

CSP hat zum Ziel einen Browser-seitigen Mechanismus zu schaffen um einige Angriffe auf Webseiten zu verhindern, hauptsächlich XSS-Angriffe.

Einschub: Was ist XSS?

XSS = Cross Site Scripting. Passiert wenn ein User ungefiltertes HTML in die Webseite einfügen kann.

<div class="comment">
  Danke für den interessanten Beitrag! <script>alert('you have been hacked')</script>
</div>

Rails löst das Problem weitgehend, aber

  • Programmierfehler weiter möglich
  • manchmal Sicherheitslücken in Gems oder Rails

Lösungsid...