Skip to content

Instantly share code, notes, and snippets.

@kkas
Last active March 17, 2018 00:40
Show Gist options
  • Save kkas/36071f45e3ef714b9f21 to your computer and use it in GitHub Desktop.
Save kkas/36071f45e3ef714b9f21 to your computer and use it in GitHub Desktop.
Responsive Images

Why Responsive Images?

  • Images consume a lot of bandwidth
  • Terrible experience when you open up a picture that does not fit your mobile screen
  • Create mobile products, do not port or convert websites to the mobile medium
  • Always try highest quality images with the fewest bytes possible
  • Use Chrome Canary to test it out with the latest tech
    • Might not be stable, though (crashes, bugs)

How to check sizes of pictures

  • Open up the devtools and open the Network tab
  • Enable Recording
  • Reload the page and see the "Size" column to confirm the sizes
  • Use filter to show only images if necessary

How to check the actual dimentions of a picture

  • Open up the devtools and open the Elements tab
  • There are two ways to do this.
    • a hard way
      • Click on the DOM that you want to inspect ( or to manipulate)
      • Type $0 in the console to access to the DOM
      • To find out the acutual width, type
$0.naturalWidth
  • an easy way
    • hoover over the image file

Size of an image

  • Total bits = pixels x bits per pixel
    • Less pixels and better compression => less bytes

Requests and Revenue

  • On average, a web page makes 56 requests for images
  • Every one of those image requests has a cost in terms of page load
  • Studies show that even very small delay in loading pages can result in a significant loss of trafic and revenue
    • By Google, a 0.4 to 0.9 second increase resulted in trafic and revenues down by 20%
    • For Amazon, every 100 milisecond increase in page load time means a loss of sales of 1%.

Relative Sizing

  • Fixed Size image
    • Looks fine when the screen size is bigger than the image size.
    • Problems
      • ウィンドウサイズを小さくした場合、イメージが一部しか表示されなくなる
      • モバイルのデバイス上において、イメージサイズがViewportよりも大きい場合、画像の全部を見るためにはスクリーンを横にスクロールする必要がでてくる
  • width: 100% (Relative Sizing)
    • ウィンドウサイズが小さい場合はOK
    • Problems
      • ウィンドウサイズを大きくした場合、イメージが汚くなる(ピクセルが荒く表示される)
  • max-width (of the image): 100%
    • 良い感じに画像が縮小・拡大され、最大でもイメージの実サイズまでしか大きくならない

Point

  • ウィンドウサイズはスクリーンサイズとイコールであるとは限らない
    • ウィンドウサイズは変わる可能性がある
  • max-widh を使うと、より大きなviewportに変更したときでも良い感じにイメージを拡大してくれる
  • レスポンシブを考慮するのであれば、スクリーンサイズは大きいものと小さいものの両方を考慮する必要がある
  • 2つ並べてイメージを表示したい場合、単純に width: 50% を使えば良い
  • これらの間に10 pixelのマージンを入れたい場合、以下のように算出すればいい。AbsoluteとRelativeサイズを組み合わせて使用する際にオススメ。
img {
  margin-right: 10px
  max-width: 426px; //画像のサイズ以上には拡大しない
  width: calc((100% - 10px)/2); // calc((100% - <M * N>) / N) ※M: マージンサイズ N: 横並びに配置する画像数
}
  • 最後の画像のmargin-rightは0pxを指定も忘れずに。
img:last-of-type {
  margin-right: 0;
}

Landscape and Portrait

  • モバイルフォンやタブレットを利用する場合、縦長(portrait)のスクリーンを利用する
  • 反対にラップトップでフルスクリーンでブラウザを利用する場合は、横長(landscape)のスクリーンである
  • しかし、モバイルフォンやタブレットの場合、縦長(portrait)から横長(landscape)に変更ができるため、その場合のサイズとコンテンツについての考慮が必要となってくる
  • 横長のイメージを縦長(portrait)で表示する場合には問題が発生する
  • レスポンシブデザインの黄金律(golden rule)は、「Don't assume the viewport size will always stay the same.」

Less Well Known CSS Units

  • 画像を常にViewportの縦サイズに合わせたい場合どうするか? イメージのサイズを100%にすればできる。ただし、HTMLのheightとbody要素のheightが100%の場合にのみ有効な方法である
  • より簡単な方法は「vh (viewport height)」ユニットを利用すること (vw (viewport width)もある)
    • 1vh = 1% of the viewport height
    • e.g. 100vh = 100% height
  • viewportの縦サイズまたは横サイズのいずれか小さい方に合わせたい場合、「vmin (viewport minimun)」を利用する。これは、viewportのheightまたはwidthのいずれか小さい方の1%となる
    • e.g. 1vmin (when height > width) => 1% of the viewport width
    • e.g. 1vmin (when height < width) => 1% of the viewport height
img {
  width: 100vmin;
  height: 100vmin:
}
  • viewport全体を、画像のへんな新宿なしで設定したい場合、「vmax (viewport max)」を利用する。vminの反対で、viewportの縦または横サイズの大きい方に合わせる
    • e.g. 1vmax (when height > width) => 1% of the viewport height
    • e.g. 1vmax (when height < width) => 1% of the viewport width
    • 以下のようにwidthとheightにこれを指定することで、レスポンシブにviewport全体にイメージを表示させることができるようになる
img {
  width: 100vmax;
  height: 100vmax;
}

Raster and Vector

  • イメージの生成方法はおおまかに2種類あり、レスポンシブイメージを考慮する場合に違いが発生する
    • Raster
      • 通常のイメージ。小さな色のドットの集合で構成されている
      • カメラやスキャナーからのイメージ、またはHTMLcanvas要素などで生成されたりする
    • Vector
      • 曲線や直線、形、色などの組み合わせで構成されているイメージ
      • Adobe Illustrator や Inkscapeなどのアプリケーションで作成可能
      • SVG(Scalable Vector Graphics)などのvector拡張子をもったイメージを利用する
  • RasterとVectorの見え方の違いの例

File Format

Compression, Optimization and Automation

sudo port install ImageMagick
sudo port install npm
sudo npm install -g grunt-cli

cd <project_dir where a package.json exists>
npm install
  • install the plugin
npm install grunt-responsive-images --save-dev
  • How to execute?
cd <rootdir_of_the_project>
mkdir images # Be sure to have the image in this dir.
grunt

https://www.npmjs.com/package/grunt-respimg

  • Image Optimization

    • ImageOptim
      • enables lossless image optimization using a number of open source tools, such as
        • PNGOUT
        • Pngcrush
        • JpegOptim
        • Gifsicle etc.
      • can be run from the CLI
      • https://imageoptim.com/
  • Image Compression

    • ImageAlpha
      • uses pngquant and some other tools for compression
      • can reduce 24-bit PNG files by applying lossy compression and converting PNG-8 plus alpha format
      • can be run from the CLI
      • https://github.com/pornel/ImageAlpha

Image Compression

Tips

Performance

  • Latency
    • Delay between request and response
    • To avoid, reduce the number of image requests, not just the size of image files
  • Every time your browser try to retrieve an images from a webserver, there are potential delays at every step of the way between your device and the web servers
  • Fundamental problem is that data cannot travel faster than the speed of light
    • Even optical fiber channel can achieve a bit better than half the speed of light
    • At best, from London to California, the latency will be around a hundred millisec.
  • For the best responsive design, performance is really important
  • Latency is the performance bottleneck for the following reasons:

How to Improve?

/* Set the image  */
background:url(xxxxx.png); display:inline-block; height:20px; width:20px }

/* Display only necessary part  */
#btn1 {background-position: -20px 0px}
  • Try to reduce the number of image size (by compressing) and the number of file requests (by CSS sprite) in order to achieve better performance

Text Problems

CSS Technics

  • Use css for graphical effects for texts, such as shadowing (which is supported by all modern web browsers), rounded corners, gradient, and animations, much better than using image hack
  • Be aware that there is a rendering cost of processing time for css

CSS background images

Symbol Charactors

Icon Fonts

  • Icon fonts are vector-graphics, so less size and more scalability.
  • Available Sites (either download it or use it online)(free & opensource)
@import url(http://zocial.smcllns.com/api/?family=zocial);

[class*="zocial-"]:before {
  ...
  text-shadow: 3px 3px 3px #aaa;
  ...
}

# in html
<li class="zocial-twitter">Twitter</li>

Inlining Images with SVG and data URIs

  • Data URIs provide a way to include a file such as an image inline as a base64 encoded string
    • format:
<img src="data:image/svg+xml;base64,[data]">

Full Responsiveness

Responding to Screen Capability & View

Pro tip: to get the maximum bang-for-your-back when optimizing your site, focus on very large images. Pick the ten largest! In particular, resizing images in CSS or HTML can be a huge problem for big images. For example: you need a 1000x1000px image file to display in a 500x500px img element on a 2x screen. If you use a 1100x1100px image, that's 100 x 100 = 10,000 wasted pixels!

srcset

  • problem of is that it can provide only one URL for one image.
  • use "srcset" attribute to let browsers to choose an alternative image depending on the viewport size and the device capabilities.
    • Pixel Density Descriptor
      • "1x" or "2x" in srcset
      • 1x is used by 1x devices, and 2x is used by 2x devices(high resolution)
<img src="xxxx_1x.jpg" srcset="xxxx_1x.jpg 1x, xxxx_2x.jpg 2x" alt="xxxxx">
* No need to warry for the fallback. browsers that do not support "srcset" attribute, they use the image that is specified in "src" attribute.
  • How to check the device ratio?
window.devicePixelRatio

sizes attribute

  • The browser knows:
    • screen resolution
    • image dementions
      • The browser parses the HTML and starts image preloading before CSS is parsed.
    • DOES NOT knows nothing about the image display size
  • specifing "sizes" attribute means that it tells the browser the sizes at which an image will be displaed
    • Therefore, the browser can retrieve the right image while parsing the HTML.
  • In theory, the browsers could get this data from CSS, but CSS parsing comes later. By putting "sizes" attribute in HTML, the browser can retrive the right image as soon as possible.
  • "sizes" attribute does not actually resize the image. You still need to do it in CSS.

In JavaScript you can get the source of an img element with currentSrc.

The sizes attribute gives the browser information about the display size of an image element – it does not actually cause the image to be resized. That's done in CSS!

The Picture Element

  • "" element can specify alternative image sources, and the browser will look from the first one to the last until it finds the one available.( depending on the device capability)
  • Syntax
## Example of source element
<picture>
  <source srcset="kittens.webp" type="image/webp">  
  <source srcset="kittens.jpeg" type="image/jpeg">
  <img src="kittens.jpeg" alt="Two grey tabby kittens">
</picture>

## Example of art direction
<picture>
  <source media="(min-width: 650px)" srcset="kitten-large.png">
  <source media="(min-width: 465px)" srcset="kitten-medium.png">
  <img src="kitten-small.png" alt="Cute kitten">
</picture>

Accessibility

  • ChromeVox
    • ChromeVox is a screen reader for Chrome which brings the speed, versatility, and security of Chrome to visually impaired users.
    • http://www.chromevox.com/
  • Lynx
    • Lynx is a fully featured World-Wide Web browser for users on both Unix and VMS platforms who are connected to those systems via cursor-addressable, character-cell terminals or emulators. That includes VT100 terminals, and desktop-based software packages emulating VT100 terminals (e.g., Kermit, Procomm, etc.).
    • http://invisible-island.net/lynx/
  • Always add "alt" attribute

Remote Debugging on Android with Chrome

Setup your android device

  • Enable USB debugging
  • (for Windows) Install OEM USB Drivers
  • Connect your device
  • Access the following in the browser (Make sure "Discover USB devices" is checked)
    • chrome://inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment