Code and Stuff

Jun 13, 2015

CSS3: Compositing

CSS3 Supports Image Compositing! The animation below uses only CSS (no Javascript, no GIF). Requires Firefox 32+, Chrome 41+.


Jan 15, 2015

Java: DNS Query

Getting information about a host or a domain in Java is actually quite simple if you use the JNDI (Java Naming and Directory Interface). This interface, available since java 1.3, offers a standardized access to a range of directory services. Among them the DNS.

Its usage can be quite simple. For instance, asking for the IP of a host is simply:

DirContext ctx = new InitialDirContext();
Attributes attr = ctx.getAttributes("dns:/www.example.com");
String ip = attr.get("a").get().toString();

Getting the MX record of a domain is just as simple:

DirContext ctx = new InitialDirContext();
Attributes attr = ctx.getAttributes("dns:/gmail.com",
                                    new String[] { "MX" });
String host = attr.get("MX").get().toString();

And so is quering a different DNS server. The following example will query google's DNS for the MX record of gmail.com:

DirContext ctx = new InitialDirContext();
Attributes attr = ctx.getAttributes("dns://8.8.8.8/gmail.com",
                                    new String[] { "MX" });
String host = attr.get("MX").get().toString();

More

More information can be found at the following sites:

Jan 2, 2014

SBS-3 to Base station Traffic Compression

Listening only to ADS-B data from an SBS-3 antenna can consist of something like 20-30KB/s of continuous data. If you have the device turned on 24/7 for a whole year this will sum up to more than half a Tera Byte of data. For most people this is just fine since it should still fall under the terms of use of most service providers or because the device is in the local network.

For others, however, it could be a problem. Take for instance a setup where the antenna will have to transmit the data via cellular network or via modem. Let's not forget that the data is outbound and on a line with 1Mbit/s out speed the basestation will eat up about 15% of the bandwidth.

Fortunately the traffic is quite repetitive and a constant flow is not really necessary. So this leaves the door open to compression and some nice people did all the work for us.

In this example the local network of the antenna is called Net A and the one of the client Net B. To compress the traffic we will need an additional computer on Net A that we will call Encoder. Here a Raspberry Pi or similar could be really ideal.

For the tunnel we will use ncat and we will only compress the outbound traffic. Assuming that the antenna has the IP 192.168.1.2, on the Encoder we will run the following command:

ncat -l 10001 -c 'ncat 192.168.1.2 10001 | gzip -c'

Assuming that the encoder's IP is 192.168.1.3, on the client in Net B we will run

ncat -l 10001 -c 'ncat 192.168.1.3 10001 | gunzip -c'
To get ncat and gzip on windows you can either install them directly or use cygwin.

now we just have to configure the basestation software to access localhost instead of the antenna and all traffic in going to be compressed.

Results

With some simple measurements, I could notice that the trick should allow you to reduce the traffic from the original 20KB/s to about 1KB/s. Since gzip will compress data in blocks the flow of data will be much less regular. Fortunately it looks like the basestation software does not care about this.

Other software

Initially I tried to use a compressed SSH tunnel. Strangely there was no reduction in the traffic size. I probably did something wrong in setting the tunnel up. Since ncat worked so well I did not bother finding out what went wrong with the SSH tunnel.

Instead of gzip one could also use other compression software like xz, bzip2, etc. Such software might have even better compression ratios. Beware, however, that some algorithm use big compression buffers and might require quite some data before actually returning something.

Links

kinetic avionics
http://www.kinetic.co.uk/
ncat
http://nmap.org/ncat/
gzip for windows
http://gnuwin32.sourceforge.net/packages/gzip.htm
cygwin
http://cygwin.org/

Apr 13, 2013

SVG Filters: ColorMatrix

The Matrix you can enter below will be multiplied against all the color vectors of the image on the right below.
RGBA1
R
G
B
A
0 0 0 0 1 1
The SVG filter that is being applied to the image is the following.
<svg width="0" height="0" xmlns="http://www.w3.org/2000/svg">
    <filter id="filterid">
        <feColorMatrix type="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 "/>
    </filter>
</svg>
To apply such a filter to an HTML element one simply has to put the SVG filter somewhere in the page and apply it with the following CSS3 code.
img {
   -webkit-filter: url(#filterid);
   filter: url(#filterid);
}

Mar 28, 2013

Battery Status (firefox)

A web page can read the level of the computer's battery (if any) and it is really easy. It is all in the window.navigator.battery object. This object has a property level that indicates the current battery level as a number between 0 and 1. There is no need to poll the value. Level changes can be tracked with the "levelchange" event. The object tells also if the battery is being charged or used and has fields with hints on charging/dischanrging times. As for the level also this values are trackable registering event handlers.

This is especially useful in web applications. For instance, with this API available, an application could be implemented so that power intensive operations like animations, audio and video are disabled, or limited to a minimum, when the battery level is getting too low. It could also return to the normal setting as soon as the power is connected.

Unfortunately, as of March 2013, I know only of Firefox that supports this W3C Candidate Recommendation.

Howto

So, here is the code. First the HTML. There is nothing that is really needed to be done in HTML to access the battery status. To display the level I simply created two DIVs, one for the whole battery the other for the current state.
<div id="battery"><div class="level"></div></div>
Also the CSS is just for the display: some round borders and backgrounds.
#battery {
  border: solid 4px darkred;
  border-radius: 8px;
  width: 80px;
  height: 200px;
  position: relative;
}

#battery .level {
  position: absolute;
  bottom: 0px;
  background-color: red;
  left:0px;
  right:0px;
}
It is the Javascript that is the most interesting. It registers an event that when triggered will update the battery indicator. Note: code uses some JQuery.
// let's be ready for webkit (they sayed they will use the prefix)
var battery = window.navigator.battery || window.navigator.webkitBattery; 

function update() {
  var level = battery.level;
  $("#battery .level").height(level * 200);

  // should probably define 3 classes, one for each color state
  if (level < 0.33) {
    $("#battery .level").css("background-color","red");
    $("#battery").css("border-color","darkred");
  } else if (level < 0.66) {
    $("#battery .level").css("background-color","yellow");
    $("#battery").css("border-color","brown");
  } else {
    $("#battery .level").css("background-color","lightgreen");
    $("#battery").css("border-color","darkgreen");
  }
}

// and finally when the DOM is ready let's update and register the event
$(function(){
  if (battery == undefined) {
    // sorry no battery status api support
    return;
  }

  update();

  // and here we register the event
  battery.addEventListener('levelchange', update, false);
});

Links

Here a few links to other people's posts about this:

Feb 26, 2013

SVG Filter Tests

Applying SVG filters to various things

Videos

Apply filter to WebRTC Webcam capture. Webcam code was taken from Mozilla.

Or on a normal video (source wikipedia http://en.wikipedia.org/wiki/File:GibraltarpediA_introduction_video.ogg);

Canvas

To test the canvas I will reuse my Image Compositing post "plasma" like animation.

Youtube

Youtube can work using flash or html5. Probably the HTML5 uses a video tag or a canvas (never actually checked that), but we are interested in the flash version. By default, if available, youtube uses flash (as of feb 2013). Click Here for the original Rhett & Link GMM video.

Problems

Mid february 2013 i tested Mac Firefox 19, Mac Chrome 25 and Windows Firefox 19
  • Chome shows some strange behaviour with animated stuff (e.g. convolution not applied)
  • Firefox SVG filters are quite slow (especially the erode and dilate)
  • Firefox SVG filters are not applied to flash videos on Windows. They are on a Mac 10.6

Feb 13, 2013

C++ Polymorphic

Used to Java I was quite surprised to discover that the RTTI of C++ works "polymorphic" only when the classes contain at least one virtual method. This means that if we have two classes, A and B where B inherits from A, and we ask for the typeid of an instance of B from a dereferenced A pointer, RTTI will tell us the type is B only if A has a virtual method otherwise it will tell us the type is A.

This is best shown in code:

#include <iostream>
#include <typeinfo>

class A { };
class B : public A { };

class VA {
  virtual void dummy(){ }; 
};

class VB : public VA { };

int main() {
  B* b = new B; // typeid is B, ok
  A* a = new B; // typeid is A!

  std::cout << "b: " << typeid(*b).name() << std::endl;
  std::cout << "a: " << typeid(*a).name() << std::endl;

  VB* vb = new VB; // typeid is VB, ok
  VA* va = new VB; // typeid is VB, just like java :-)

  std::cout << "vb: " << typeid(*vb).name() << std::endl;
  std::cout << "va: " << typeid(*va).name() << std::endl;
  return 0;
}
will output the following:
b: 1B
a: 1A
vb: 2VB
va: 2VB
The second line tells us that the type is A even if we created the object with "new B".

This implies that we will not be allowed to dynamic_cast an A pointer to a B one. gcc will reports that the cast is not permitted becase the "source type is not polymorphic".

A* a = new B;
B* c = dynamic_cast<B*>(a); // compilation error
It is, however, perfectly fine to cast the classes with the virtual method:
VA* va = new VB;
VB* vc = dynamic_cast<VB*>(va);

Jan 30, 2013

Animating SVG Filters applied to HTML elements

Animating CSS3 filters is possible. While the ones defined directly in CSS can be animated with CSS3 transitions, SVG filters require another approach. We can use SVG Animations. It is not as trivial as the transitions but still quite simple.

Setup

To animate SVG filters we simply have to put an animate tag as child of the element we want to animate. Animations can be timed, concatenate and even started with javascript.

Here an example on how to animate the intercept of all the RGB transfer functions of the feComponentTransfer filter from -1 to 1 and back repeatedly.

<svg width="0" height="0" xmlns="http://www.w3.org/2000/svg">
  <filter id="myfilter">
    <feComponentTransfer>
      <feFuncR type="linear" slope="1" intercept="-1">
        <animate attributeName="intercept" attributeType="XML" 
            begin="0s" dur="4s" repeatCount="indefinite" 
            values="-1;1;-1"/>
      </feFuncR>
      <feFuncG type="linear" slope="1" intercept="-1">
        <animate attributeName="intercept" attributeType="XML" 
            begin="0s" dur="4s" repeatCount="indefinite" 
            values="-1;1;-1"/>
      </feFuncG>
      <feFuncB type="linear" slope="1" intercept="-1">
        <animate attributeName="intercept" attributeType="XML" 
            begin="0s" dur="4s" repeatCount="indefinite" 
            values="-1;1;-1"/>
      </feFuncB>
    </feComponentTransfer>
  </filter>
</svg>
As per usual the filter is applied to the dom element with some CSS:
<style type="text/css">
#someElement {
   filter: url(#myfilter);
   -webkit-filter: url(#myfilter);
}
</style>

Triggering animations on hover (Firefox)

Unfortunately setting the begin attribute to mouseover or click does not work. This probably because the filter is not applied to an SVG image but an HTML DOM element.

We will, therefore, need some Javascript to simulate a CSS3 Transition for an SVG filter. Looks like there is some problems with SVG filter animations in chrome, so this only works properly with firefox.

JQuery has the very handy hover method to add the two event handlers. As implemented the hover transitions must be very short (0.5s or so). A cleaner implementation should check the actual position of the one animation to start the other. This would allow smoother transition with no jumps when the transition happens before the previous one ends.

$(function() { // on DOM ready register the events
  $("#theItem").hover(function(event){
    // stop the out event
    $("#myfilter animate").get(1).endElement();
    // start the in one
    $("#myfilter animate").get(0).beginElement();
  }, function(event){
    $("#myfilter animate").get(0).endElement();
    $("#myfilter animate").get(1).beginElement();
  });
});
The filter will need this time two animation with undefined begin and end times. An animated saturation filter would look like this:
<svg width="0" height="0" xmlns="http://www.w3.org/2000/svg">
  <filter id="myfilter">
    <feColorMatrix type="saturate" values="0">
      <animate attributeName="values" attributeType="XML" 
                  begin="indefinite" end="indefinite" dur="0.5s" 
                  fill="freeze" from="0" to="1"/>
      <animate attributeName="values" attributeType="XML" 
                  begin="indefinite" end="indefinite" dur="0.5s" 
                  fill="freeze" from="1" to="0"/>
    </feColorMatrix>
  </filter>
</svg>
On firefox moving the mouse over the image should add color to it.

Chrome Vs. Firefox

With CSS3 SVG Filters firefox seams to work better. It appears to implement more stuff. I found three things where Chrome appears to have some problems:
  • Animating some of the filters, for instance the ColorMatrix's values attribute (but I'm not sure if it has to)
  • Support for some common attributes of SVG filters (result, X, Y, Width, Height)
  • Strangely, when called while handling some specific DOM event, the beginElement function will run the animation only the first time

Jan 17, 2013

HTML5 Range Input Hack (Firefox)

UPDATE: Firefox 23 added support for the input range

Firefox does not implement the input type range yet. So here's a quick hack that creates a scrollbar for them. The code is implemented using JQuery. I'm sure there are plugins for JQuery that do this, but wanted to try my idea.

WARNING: Did not test it much and the range input needs all attributes (min, max, step)

The idea is pretty simple. For each input element with type range do the following:

  1. Create a div of same size as the input and set its overflow attribute to scroll
  2. Add a horizontally bigger element to this div
  3. Add a scroll event listener to the div that will:
    1. Compute the percentual of scroll
    2. Scale that to the min, max and step values of the input range
    3. Set the range value to the scale value
    4. inform the input it changed
  4. Make the input invisible by setting its opacity to 0 and position it somewhere far away (left:-5000, top:-5000). Do NOT set the display value to none!
function makeRange(dummy, element) {
  if ($.browser.mozilla) {
    var width = $(element).width();

    var minimum = +$(element).attr("min");
    var maximum = +$(element).attr("max");
    var step = $(element).attr("step");
    var size = maximum - minimum;
    var value = $(element).val();

    // 1 and 2
    var newDiv = $('<div style="overflow:scroll; display:inline-block;width:' + width + 'px; height:15px;">\
                    <div style="height:0px;width:' + (width * 4) + 'px">&nbsp;</div></div>');
    newDiv.insertBefore($(element));

    // scroll to initial value
    newDiv.scrollLeft(width * 3 *((value - minimum) / size));
    
    // 3
    newDiv.scroll(function(e){

      // 3.1
      var width = $(this).children().first().width() - $(this).width();
      var value = this.scrollLeft / width;

      // 3.2
      var size = maximum - minimum;
      var fval = minimum + size * value;
      var ival = Math.floor(fval / step) * step;
      ival = ival.toFixed(Math.ceil(Math.abs(Math.log(step))));
      
      // 3.3
      $(element).val(ival);
      
      // 3.4
      $(element).trigger('change');
    });

    // 4
    $(element).css("position","absolute");
    $(element).css("opacity","0");
    $(element).css("left", "-5000px");
    $(element).css("top", "-5000px");
  }
}

// call this when the Document is loaded
$(function(){
    // for each input element of type range 
    $("input[type=range]").each(makeRange);
});
If this method is used in a page where ranges are create dynamically in javascript, make sure to run it only on the newly created range. Otherwise you will end up with duplicate scrollbars on existing ranges.

Jan 16, 2013

Miniature Effect with single SVG Filter (Firefox)

In a previous attempt to create a minuature filter for firefox I used multiple DIVs each showing a different level of blur. This works fine, especially if Webkit support is needed, but it is a little complicated to implement when needed multiple times.

When firefox support alone is ok, the whole effect can be implemented in one single SVG filter. We just have to combine the correct ones.

This new implementation uses merging of multiple filter steps. Currently this only works in Firefox. The filter is:

<svg width="0" height="0" xmlns="http://www.w3.org/2000/svg">
  <filter id="svgFilter3153195357290276084">
    <feGaussianBlur y="0" height="100%" in="SourceGraphic" stdDeviation="8" result="b1"/>
    <feGaussianBlur y="5%" height="90%" in="SourceGraphic" stdDeviation="7" result="b2"/>
    <feGaussianBlur y="10%" height="80%" in="SourceGraphic" stdDeviation="6" result="b3"/>
    <feGaussianBlur y="15%" height="70%" in="SourceGraphic" stdDeviation="5" result="b4"/>
    <feGaussianBlur y="20%" height="60%" in="SourceGraphic" stdDeviation="4" result="b5"/>
    <feGaussianBlur y="25%" height="50%" in="SourceGraphic" stdDeviation="3" result="b6"/>
    <feGaussianBlur y="30%" height="40%" in="SourceGraphic" stdDeviation="2" result="b7"/>
    <feGaussianBlur y="35%" height="30%" in="SourceGraphic" stdDeviation="1" result="b8"/>
    <feGaussianBlur y="40%" height="20%" in="SourceGraphic" stdDeviation="0" result="b9"/>
    <!-- the center needs to be unblurred (identity component transfer) -->
    <feComponentTransfer x="0" y="45%" width="100%" height="10%" in="SourceGraphic" result="a"/>

    <feMerge x="0" y="0" width="100%" height="100%" >
      <feMergeNode in="SourceGraphic"/>
      <feMergeNode in="b1"/>
      <feMergeNode in="b2"/>
      <feMergeNode in="b3"/>
      <feMergeNode in="b4"/>
      <feMergeNode in="b5"/>
      <feMergeNode in="b6"/>
      <feMergeNode in="b7"/>
      <feMergeNode in="b8"/>
      <feMergeNode in="b9"/>
      <feMergeNode in="a"/>
    </feMerge>
  </filter>
</svg>

In the first part of the filter a set of 8 gaussian blurs, of always smaller section of the source image, are created. In the second one, they are composed with the simple alpha composition.

As in the original post the filter is applied using CSS with something like:

img, video {
   filter: url(#filterId);
}
This time there is no need for a container DIV nor a positioning one. The filter can be applied to any DOM element.

Dec 24, 2012

CSS3 SVG Filters (1)

CSS3 Filters (not to be confused with the, now deprecated, Microsoft CSS filters) are used to post-process the rendering of parts of the DOM. They are still a Draft and might change in the future. However, firefox and webkit have already some implementations.

Filters are enabled on one or more DOM elements with the CSS property filter. There are two quite different ways to implement filters. The more immediate one is by adding one or more filter directly in the CSS. The other is by specifying an URL to a SVG filter. This latter way is much more flexible and feature rich. It requires, however, that the browser supports SVG. Fortunately all major ones do so.

Example/Generator

In this example only some SVG filters are shown.

FilterRange
Blur: Positive value (pixels)
Saturation: Between 0 and 1
Brightness: Positive
Sepia: Positive
Hue Rotation: Any number of degrees

CSS

#element {
  filter: url(#myfilter);
  -webkit-filter: url(#myfilter);
}

HTML

Somehwere in the HTML code we have to place this SVG tag. Since it's size is 0x0 it should not affect the rendering of the page. The only child of this SVG is the filter we set in the CSS (myfilter).
<svg width="0" height="0" xmlns="http://www.w3.org/2000/svg">
  <filter id="myfilter">
    <!-- Blur -->
    <feGaussianBlur in="SourceGraphic" stdDeviation="1"/>
    
    <!-- Saturation -->
    <feColorMatrix type="saturate" values="1"/>
    
    <!-- Brightness -->
    <feComponentTransfer>
      <feFuncR type="linear" slope="1"/>
      <feFuncG type="linear" slope="1"/>
      <feFuncB type="linear" slope="1"/>
    </feComponentTransfer>

    <!-- Sepia (with color matrix:
    (0.393+0.607*[1-0]) (0.769-0.769*[1-0]) (0.189-0.189*[1-0]) 0 0
    (0.349-0.349*[1-0]) (0.686+0.314*[1-0]) (0.168-0.168*[1-0]) 0 0
    (0.272-0.272*[1-0]) (0.534-0.534*[1-0]) (0.131+0.869*[1-0]) 0 0
    0 0 0 1 0
    -->
    <feColorMatrix type="matrix"
               values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0"/>
    
    <!-- Hue Rotation -->
    <feColorMatrix type="hueRotate" values=" 0"/>
  </filter>
</svg>

Chrome Problems

While implementing the scripts of this post I encountered a problem with chrome. When changing some of the filters by modifying the DOM with javascript the image was not updated. I noticed however that when the blur was changed, the filter was applied. A quick workaround was, therefore, to change the blur and set it back at each value change.

A probably better solution to the problem is to remove and re-add the filter.

Nov 12, 2012

Java Snippets

Just some code snippets that I found useful. Not necessarily the best or fastest solutions.

Generics

Return Types

To get the compiler to understand a generic return type, simply add a dummy class parameter.
public static <A> A someMethod(Class<A> dummy) {
}

// calling the method
someMethod(Double.class);

Collections

Single Element List

Create a list of one single element.
Arrays.asList(element);

Iterable Iterator

Looping over an iteartor with a foreach is not possible. An Iterable is needed.
/**
 * Put this method in a Utility class. It can then be imported as class 
 * or statically.
 */
public static <T> Iterable<T> toIterable(final Iterator<T> the_iterator) {
   return new Iterable<T>() {
      public Iterator<T> iterator() { 
         return the_iterator;
      }
   };
}

...

for(T t : toIterable(an_iterator)) {
   // do something
}

Foreach on XML NodeList elements

Creating simple Iterable will allow us to iterate over NodeLists

Iterable<Element> toIterable(final NodeList list) {
   return new Iterable<Element>() {
      @Override public Iterator<Element> iterator() {
         return new Iterator<Element>() {
            int position = 0;

            @Override public void remove() {
               throw new UnsupportedOperationException();
            }

            @Override public Element next() {
               if (!hasNext()) throw new NoSuchElementException();
               return (Element) list.item(position++);
            }
     
            @Override public boolean hasNext() {
               // move to next
               while(position < list.getLength() && !(list.item(position) instanceof Element)) ++position;
               return position < list.getLength();
            }
         };
      }
   };
}

// used 
Element someElement = ...;
for (Element child : toIterable(someElement.getChildNodes()) {
   /// TODO something
}

Loops

Multiple nested loops break

// given a matrix of size n x k
// we want to know if it contains a value greater than val
double val = 1;
boolean found = false;

label: for(int i = 0; i < n; ++i) {
   for(int j = 0; j < k; ++j) {
      if (matrix[i][j] > val) {
         found = true;
         break label; // get out of both for loops
      }
   }
}
Note: this post might grow in time

Sep 15, 2012

CSS3 Miniature Effect

Miniature effect

It has been implemented using 6 divs stacked one on top of the other using css. The higher the z-index, the narrower and less blurred it is. The blur is applied using SVG filters.

The six layers are splitting the picture in 13 stripes. The mid one is not blurred.

The original picture is:

The code

Layer 1
Lots of Blur
Layer 2
Little Blur
Layer 3
No Blur
As explained earlier the effect consists of 6 div tags stacked, blurred and sized with css. This layers are enclosed in two more divs. One for the positioning and the outer one to clip and add the border. On the right an example is shown on how the layers are stacked and sized (only 3 layers shown).

Blurring is obtained by applying an SVG filter to the HTML content via the CSS filters. SVG filters can be embedded in the HTML page, but should be without the namespace (not valid XML). For convenience only two of the 5 filters are shown.

<svg width="0" height="0" xmlns="http://www.w3.org/2000/svg">
  <filter id="blur5">
    <feGaussianBlur in="SourceGraphic" stdDeviation="5"/>
  </filter>
  <filter id="blur4">
    <feGaussianBlur in="SourceGraphic" stdDeviation="4"/>
  </filter>
  ...
</svg>
In HTML the 6 layers look like the following:
<div class='border'>
   <div class='positioning'>
      <div class='layer1'></div>
      <div class='layer2'></div>
      <div class='layer3'></div>
      <div class='layer4'></div>
      <div class='layer5'></div>
      <div class='layer6'></div>
   </div>
</div>

The picture used in the example is 447 pixel wide and 325 pixel high. We want the central layer to be of half the hight of the visible part of the other layers. This will give us 13 horizontal slices of the original picture. Each slice is 25 pixel high (325/13).

.positioning > div {
   background: url("https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEirUSB_EIev8C1LFSu6D74rhXEy_2o66xjt9FJZmoQqvIyAUomOh0ID8J2zW_3L_yVLlI8ncI6geDspX0bNdI642OzNXbe5oKRzQv6D8VLzPCscAyAfIMm1pgJbJYJYRYJl3COPuyrw27I/s1600/leit.jpg");
   position: absolute;
   width: 447px; /* this is the width of the picture */
   left: 0px;
}

.positioning {
   /* we shift the picture to cut 10px away (see border) */
   margin: -10px; 
   position: relative;
   height: 325px;
   width: 447px;
}

.border {
   /* cut away a 10px border by making div smaller */
   overflow: hidden; 
   height: 305px;
   width: 427px;
}

.layer1 { 
   /* inherited position absolute from .positioning > div */
   z-index:1;
   top: 0px;
   bottom: 0px;
   background-position: 0px -100px;
   filter: url(#blur5);
   -webkit-filter: blur(5px);
}

.layer2 {
   z-index:2;
   top: 25px; bottom: 25px;
   /* align background images */
   background-position: 0px -25px;
   filter: url(#blur4);
   -webkit-filter: blur(4px);
}

.layer3 {
   z-index:3;
   top: 50px; bottom: 50px;
   background-position: 0px -50px;
   filter: url(#blur3);
   -webkit-filter: blur(3px);
}

.layer4 {
   z-index:5;
   top: 75px; bottom: 75px;
   background-position: 0px -75px;
   filter: url(#blur2);
   -webkit-filter: blur(2px);
}

.layer5 {
   z-index:5;
   top: 100px; bottom: 100px;
   background-position: 0px -100px;
   filter: url(#blur1);
   -webkit-filter: blur(1px);
}

.layer6 {
   z-index:6;
   top: 125px; bottom: 125px;
   background-position: 0px -125px;
   /* no blur */
}

And that's it. Not all pictures give a nice result with this effect. It is out of the scope of this post to address the selection of good pictures for the miniature effect.

UPDATE: Single filter implementation that does not need any additional divs (Only firefox)

Jun 19, 2012

CSS Units

CSS defines a lot of units for different type of measures. Here a few examples and some explanations. The interactive parts should work on Firefox and webkit (where applicable), did not test on IE and Opera.

Length units

Absolute

The main absolute length (size) unit, when working for the screen, is the pixel (px).

CSS defines also some other absolute length units. These are more useful for print, but can be used also on a display (discouraged). The discouraging holds also the other way around: px should be used with care when printing.

pt
3/4
mm
25.4/96
pc
1/16
cm
2.54/96
in
1/96
1px
px
4/3
mm
25.4/72
pc
1/12
cm
2.54/72
in
1/72
1pt
px
96/25.4
pt
72/25.4
pc
6/25.4
cm
0.1
in
10/2.54
1mm
px
16
pt
12
mm
25.4/6
cm
2.54/6
in
1/6
1pc
px
96/2.54
pt
72/2.54
mm
10
pc
6/2.54
in
1/2.54
1cm
px
72
pt
96
mm
25.4
pc
6
cm
2.54
1in

Font Relative

0.
x
1ex
1em
1ch
All major browsers support at least two font relative units: em and ex. As the "image" on the side shows, the em is the total font height while the ex is usually the height of the x character (one exception is when the font doesn't have the letter x). The font that is used for this sizes is the one applied to the tag (therefore the inherited one if none is explicitly specified).

Another font relative measure of units is the rem. The rem (root em) is the same as the normal em but related to the root element.

And there is also ch. This last font related unit is the advancement of the character '0' (zero) of the current font. In fonts that are not monospaced the advancement of a character depends of the character (see below).

00000mmmm

The ch unit is currently (June 2012) not supported by webkit browsers.

Viewport relative

CSS3 introduces also viewport relative units: vh, vw and vmin.
1vh = 1% of the height of the initial viewport
1vw = 1% of the width of the initial viewport
1vmin = 1% of the smallest between width and height of viewport

Percent

One more unit is the percent. Percents are relative to something. In the case of fonts they are related to the parent. For lengths (for instance: width and top), the percent, is related to the size of the first positioned element, or when none, to the size of the whole document.

Rotation Units

Rotation units are used, for instance, in transformations and radial gradients.
1turn
1rad
10deg
10grad
1 turn equals
2π rad
360 deg
400 grad
1 rad equals
1/2π turns
180/π deg
200/π grad
1 deg equals
1/360 turns
π/180 rad
9/10 grad
1 grad equals
1/400 turns
π/200 rad
10/9 deg
Move the mouse over the units on the left

Other units

CSS defines also units for pixel density, time (s, ms), frequencies (hz, khz), color, etc. I will not cover them here since quite trivial (time and frequencies) or enough complex to deserve a separate post (color, densities).

Mixing Units

Finally, there is another very nice feature that plays a role here. Let's assume we are using an element that has width of 50% wide and has a border of 10px. What if we want to place beneath it another element with same width but no border. Setting a width of 50% would make it 20px to narrow (2 borders of 10px) and the actual width depends on the size of the container. Fortunately CSS3 can perform computation. We can set the width of the second element to "calc(50% + 20px)".
width:50%; + 2x 10px border
width:50%
width: calc(50% + 20px)

The source code (without background colors) for the example above is

<div style="width:50%; border:10px solid">width:50%; + 2x 10px border</div>

<div style="width:50%;">width:50%</div>

<div style="width:-moz-calc(50% + 20px); width:-webkit-calc(50% + 20px); width:calc(50% + 20px);">width: calc(50% + 20px)</div>

Further reading

You can get some more information about units here:

http://www.w3.org/TR/css3-values
https://developer.mozilla.org/en/CSS/length

Jun 8, 2012

CSS3 Layout - columns

With CSS3 multi column (http://www.w3.org/TR/css3-multicol) you can create content that is organized in columns without having to split it yourself or use a javascript library to do it for you. You simply have to set the column-count or the column-width parameter of a tag and it's content will be shown in columns. Firefox and Webkit based browsers require the vendor prefix. The details of the columns can be controlled with various other parameters. These include setting the width of each column, the gap between the columns and a separator line.

Firefox does not fully implement columns. The support is limited to splitting content, but the flow control (column brake and span) is not yet implemented.

Example


Columns: 2, 3, 100px
Gap: none, default, wide
(not supported by firefox)

Result

/* a block of something */

Here some text from Wikipedia's css page: Cascading Style Sheets (CSS) is a style sheet language used for describing the presentation semantics (the look and formatting) of a document written in a markup language. Its most common application is to style web pages written in HTML and XHTML, but the language can also be applied to any kind of XML document, including plain XML, SVG and XUL.

CSS is designed primarily to enable the separation of document content (written in HTML or a similar markup language) from document presentation, including elements such as the layout, colors, and fonts. This separation can improve content accessibility, provide more flexibility and control in the specification of presentation characteristics, enable multiple pages to share formatting, and reduce complexity and repetition in the structural content (such as by allowing for tableless web design). CSS can also allow the same markup page to be presented in different styles for different rendering methods, such as on-screen, in print, by voice (when read out by a speech-based browser or screen reader) and on Braille-based, tactile devices. It can also be used to allow the web page to display differently depending on the screen size or device on which it is being viewed. While the author of a document typically links that document to a CSS style sheet, readers can use a different style sheet, perhaps one on their own computer, to override the one the author has specified.

code

div.cols {
   -moz-column-count:2;
   -webkit-column-count:2;
   column-count:2;
   -moz-column-count:3;
   -webkit-column-count:3;
   column-count:3;
   -moz-column-width:100px;
   -webkit-column-width:100px;
   column-width:100px;
   -moz-column-rule: solid black 1px;
   -webkit-column-rule: solid black 1px;
   column-rule: solid black 1px;
   -moz-column-gap:0px;
   -webkit-column-gap:0px;
   column-gap:0px;
   -moz-column-gap:4em;
   -webkit-column-gap:4em;
   column-gap:4em;
}

div.cols .somechild {
   /* not supported by firefox as of June 2012  */
   -webkit-column-span:all;
   column-span:all;
}


div.cols p:first-of-type {
   /* not supported by firefox as of June 2012  */
   -webkit-column-break-before:always;
   break-before:column;
   /* not supported by firefox as of June 2012  */
   -webkit-column-break-after:always;
   break-after:column;
}

May 27, 2012

CSS3 Reflection (Webkit & Firefox)

This effect will only work with recent versions of firefox and webkit based browsers.

Howto

Given following HTML:
<div id="someid">
   <img src="image url" />
<div/>
we want "someid" to have a reflection below. The method uses only CSS to implement the effect. No changes to the HTML and no javascript required.

In the following example the image is 300px wide and 247px high.

Webkit

Webkit browsers (for instance safari and google chrome) have the very simple yet apparently not standard, -webkit-box-reflect css property.
#someid {
   /* need some space for the reflection */
   margin-bottom: 120px;

   /* the gradient makes the reflection fade out */
   -webkit-box-reflect: below 0px -webkit-linear-gradient(bottom, rgba(255,255,255,0.3) 0%, transparent 40%, transparent 100%);
}

Firefox

With firefox we can use the element image (an images of a dom element) as background of the vertically flipped before pseudo element.
#someid {
   position: relative;
   /* need some space for the reflection */
   margin-bottom: 120px;
}

#someid:before {
   content:""; /* needed or nothing will be shown */

   background: -moz-linear-gradient(top, white, white 30%, rgba(255,255,255,0.9) 65%, rgba(255,255,255,0.7)) 0px 0px, 
               -moz-element(#someid) 0px -127px no-repeat;

   -moz-transform: scaleY(-1); /* flip the image vertically */
   position:relative;
   height:140px;
   width: 360px; /* should be > image width + margin + shadow */
   top: 247px;
   left:0px;
}
To make the before pseudo element coordinates relative to the someid div we have to change the positioning. The offset of the element background (-127px) is the height of before pseudo element (140px) - (the height of image (247px) + border of div (20px)). Note that the firefox solution works only when the page has a solid background. The color of the background has to be the same as the one of the :before pseudo element's gradient.

Since all properties that have been used for the reflection, and that have a visible effect, are all vendor specific, the two method don't mess with each other.

Video

Specs say that the two different methods will update if the content changes. Therefore they should work with video, and they do!

Firefox Glitch

Sometimes, firefox will render the gradient slightly smaller than the element background, resulting in a small line after the reflection fade out. To avoid that we can use a 1px padding on the top and bottom of the pseudo element and set the clipping and origins of the two backgrounds differently:
padding: 1px 0px;
background-origin: border-box, content-box;
background-clip: border-box, content-box;