eleqtriq

CSS Chocolate-Bar

Bevel, Dropshadow, Gloss und Glow sind Designers gestalterische Schokoriegel - alle wissen, dass man sie tunlichst meiden sollte, aber von Zeit zu Zeit können wir halt nicht wiederstehen. Die größte Kalorienbombe im Sortiment ist dabei 3-D. Ahhh 3D - was wäre damit alles möglich: Paletten tauchen aus der Tiefe auf wie Raumschiffe, entfalten Roboterarmen gleich ihre Menüs, gleiten majestätisch in den Orbit...

Noch wird es eher als Kuriosum für Nerds wahrgenommen, aber im Moment liegt beim W3C ein Working-Draft für die 3-dimensionale Transformation von CSS-Elementen vor. Und dieser Draft ist vielversprechend. Öffnet das folgende Beispiel, um zu sehen, was man mit 4 DIVs ohne eine Zeile Javascript machen kann:

Beispiel öffnen

Bevor Ihr nun loszieht um endlich die ultimative Startrekmatrixminorityreport-Navigation zu bauen, von der Ihr geträumt habt, seitdem Ihr mit 14 das erste Millenium-Falcon Poster an die Wand gepinnt habt: wie immer hat die Sache einen Haken. Da es sich um einen Draft handelt, ist die Browserunterstützung noch verschwindend gering. Genauer gesagt: Safari und zwar nur auf iPad, iPhone, iPod-Touch und unter Leopard. Das könnte sich aber schon bald ändern: Es ist zu erwarten, dass die meisten auf Webkit basierenden Browser in näherer Zeit nachziehen werden. Gerade für Entwickler auf den diversen mobilen Plattformen ergeben sich dann völlig neue Möglichkeiten, denn Webkit ist hier bekanntlich stark vertreten. Designer, die mit der Entwicklung von HTML-Apps für Mobilplattformen beschäftigt sind sollten sich also schonmal in Stellung bringen. Ich werde in dieser kleinen Serie versuchen, einen kurzen Überblick über den derzeitigen Stand von 3D CSS-Transformationen zu geben. Dieser erste Teil beschäftigt sich mit den Basis-Attributen. Im zweiten Teil werde ich dann näher auf Transformationsmatrizen eingehen. Im letzen Teil lernen wir an einem kleinen Beispiel 3D-CSS in Verbindung mit Javascript kennen. Im Vorbeigehen werden wir uns dabei etwas mit höherer Mathematik (Quaternionen irgendwer?) und natürlicher Objektrotation beschäftigen.

Meine DIVs in 3D???

CSS 3D Transformationen sollen dem Designer ermöglichen, CSS-Elemente nicht nur in der Fläche (x, y, top, left, right, bottom), sondern auch in der Tiefe (z) zu verzerren. Das mag erstmal nach Spielerei aussehen, kann aber, geschickte Verwendung vorausgesetzt, durchaus praktischen Mehrwert bringen. CSS-3D-Transformationen können, besonders in Verbindung mit CSS-Transitions, dazu beitragen, ein Interface besser in einzelne Abschnitte zu gliedern und gleichzeitig die Wechsel zwischen diesen Abschnitten nachvollziehbar zu machen.

Außerdem: ich ziehe es vor, viele Werkzeuge im Koffer zu haben. Alle Hilfsmittel, die mir erlauben, ein Nutzererlebnis zu bereichern sind mir Willkommen. Gerade im Bereich mobiler interfaces bin ich dankbar für jedes Instrument das hilft, mit der wertvollen Ressource Bildschirmfläche zu haushalten.

Die Situation

Um die Beispiele ansehen zu können, braucht Ihr einen Browser, der CSS 3D-Transformationen versteht. Derzeit sind das:

Der aktuelle Nightly-Build von Webkit für Windows unterstützt leider noch keine CSS3D-Transformationen. Ich kann nur dazu raten, immer mal wieder zu überprüfen, ob sich der Funktionsumfang geändert hat.

Derzeit sind CSS 3D Transformationen also vor allem für Entwickler interessant, die HTML-Apps für die iPhone/iPad-Plattform entwickeln wollen.

Welche Browser werden den Standard unterstützen?

Es ist am wahrscheinlichsten, dass zuerst weitere Webkit-basierte Browser den Standard übernehmen. Webkit liegt neben Safari auch Googles Chrome zugrunde. Im Desktop-Bereich ist Webkit zwar nicht so dominant, auf Smartphones ist es allerdings die meistverbreitete Rendering-Engine, wenn auch in stark voneinander abweichenden Ausprägungen.

Step by Step Walkthrough:

Designer mit einem Hintergrundwissen aus dem 3D-Animationsbereich sollten keine allzu hohen Erwartungen stellen: es gibt es z.B. weder eine Kamera, noch Shader oder Lichtquellen. Die Navigationsmöglichkeiten sind ebenfalls sehr eingeschränkt, da der Standpunkt nicht rotiert werden kann. Auch Designern, die schon mit 3D-Modelling zu tun hatten, werden einige Konzepte sehr Abstrakt erscheinen (was sind Transformationsmatrizen?) auch die Wechelwirkung zwischen dem 3D-Element und den übrigen Elementen auf der Seite ist nicht unbedingt immer plausibel (wie verhalten sich Floats? Was ist mit Margins?).

Aber bevor wir weitermachen, spielt am besten erst einmal mit dieser Demo herum. Hier könnt Ihr die einzelnen Attribute verändern und die Wirkung dann auch direkt erleben. Das hilft hoffentlich, die abstrakte Materie etwas zu veranschaulichen.

Beispiel öffnen

Dann wollen wir also mal ein einfaches HTML-Dokument anlegen:

<div id="container"> <div id="child"> </div> </div>

Als nächstes soll das div#child gedreht, skaliert und verschoben werden. Vorher müssen wir dem div#parent allerdings mitteilen, dass es auf seine Kinder eine räumliche Darstellung anwenden soll (beachtet das herstellerspezifische Präfix "-webkit-" vor allen CSS-Attributen). Der entsprechende Stylesheet:

div#container{ -webkit-perspective: 250px; -webkit-perspective-origin: 50% 80%; }

Diese beiden Angaben bereiten lediglich unsere Bühne vor. Keine der Angaben bewirkt eine Veränderung von "container". Wir legen hier nur fest, wie Kindelemente von "container" gerendert werden.

Das Konzept hinter „perspektive„ ist nicht ganz leicht zu verstehen. Stellen wir uns vor, dass zwischen dem Betrachter und der z=0 Ebene eine Pyramide wäre (Siehe Abbildung), dann wäre „Perspective” die Entfernung der Pyramide, von der Basis bis zur Spitze. Man kann Perspective mit der Änderung des Bildwinkels am Kamera-Objektiv vergleichen, eine Verzerrung und Streckung in der Tiefe. Je größer dieser Wert, desto spitzer die Pyramide und desto mehr entspricht die Darstellung der untransformierten Größe, weil die Verzerrung bei der Projektion weniger stark ausfällt. Als Faustregel gilt: Wert zwischen 700 und 1000 werden als "normal" empfunden und sind eine gute Ausgangsbasis.

„perspektive-origin” legt die Koordinaten des Perspektivmittelpunktes fest. Stellen wir uns kurz vor, wir würden eine Kamera installieren um unsere 3D-Szene zu Photografieren: „perspektive” wäre in diesem Falle der Bildwinkel am Kameraobjektiv, mit „Origin” werden die x- und y-Koordinate der Kamera festgelegt. In unserem Beispiel haben wir für „Origin” einen prozentualen Wert verwendet. Es ist aber ebenso gestattet, den Wert in anderen Maßeinheiten (px, cm, in, em etc..) oder absolut (left, top, right, bottom, center) anzugeben.

Wir haben nun die Bühne vorbereitet, kommen wir also zum Kindelement, welches transformiert werden soll:

div#child{ -webkit-transform-origin: 50% 50% 50%; -webkit-transform: perspective(0) translate3d(50px, 40px, 80px) scale3d(1, 2, 0) rotate3d(0, 1, 0, 45deg); -webkit-transform-style: preserve-3d; }

transform-origin:

Mit dem "transform-origin" wird der Mittelpunkt von dem die Transformation ausgeht festgelegt. Für die zulässigen Maßeinheiten gelten dieselben Regeln wie für die Angaben zur "perspective". Ein Z-Wert ist in der Spezifikation ausdrücklich vorgesehen, hatte aber bei keinem meiner Experimente eine Auswirkung.

transform: ...

Dieses Attribut fasst alle Transformationen zusammen:

transform: perspective(val)

Die Kurzversion von „perspective:val”, diesmal nicht erst auf dem Container sondern direkt auf dem Objekt. Die Deklaration wirkt sich also direkt auf den Träger aus. Falls es schon eine "perspective"-Deklaration auf dem Parent-Objekt gab, addieren sich die beiden Werte.

transform: translate3d(x, y, z):

Eine perspektivische Verschiebung auf der entsprechende Achse

transform: scale3d(x, y, z)

Skaliert das Objekte auf der jeweiligen Achse. Ein Wert von 1 bedeutet dass keine Skalierung stattfindet. Da ein Blockelement keine Dicke hat, scheint eine Skalierung auf der Z-Achse sinnlos. Bedenkt aber bitte, dass es z.B ohne weiteres möglich ist z. B. eine Gruppe von DIVs zu erstellen, die einen Würfel bilden. Diese Gruppe könnte anschließend auch in der Tiefe skaliert werden.

transform: rotate3d(x-vektor, y-vektor, z-vektor, winkel)

Eine Rotation um eine Vektorachse: zuerst wird der Vektor, um den die Rotation stattfinden soll festgelegt. Wichtig ist dabei das Verhältnis der Vektorwerte für x, y und z zueinander, nicht ihre Einzelwerte. D. h. rotate3d(5, 6, 10, 45deg) wird denselben Effekt haben wie rotate3d(50, 60, 100, 45 deg). Der letzte Wert ist dann der eigentliche Winkel, der in Grad (deg) und in Radian(rad) angegeben werden kann.

-webkit-transform-style:

Dies ist wieder ein Attribut, das sich erst auf das Kindelement auswirkt. 2 Werte sind möglich: "preserve-3d" und "flat".

Es gibt noch weitere Transformationen, die ich an dieser Stelle nicht aufgeführt habe, weil ich denke, dass ihre Bedeutung selbsterklärend ist:

Bleibt noch die Transformationsmatrix matrix3d(…), die ich das nächstemal etwas ausführlicher behandeln werde.

Bevel, Dropshadow, Gloss and Glow are designers chocolate-bar - everybody knows they should be avoided, but sometimes we can't resist. The biggest calorie-bomb is everything 3-D. Ahhh 3D - think of all the things it could make possible for us: palettes appearing out of the deep like spaceships, unfolding their menus like roboter-arms, then gliding majestically into the orbit...

Considered a curiosity for nerds by the most, right now a working draft for 3 dimensional transformation of css elements is proposed to the W3C and this draft is promising: open the example below to see what can be achieved with 4 divs (no further javascript necessary):

Open Example

Anyway, before you launch your editor to build the ultimate startrekmatrixminorityreport-navigation you alway dreamt of since you pinned this millenium-falcon poster onto your wall at the age of 14: of course there's a catch. As it's only a draft right now, browser-support is still homeopathic. To be concrete: Safari on iPad, iPod-Touch and Leopard. But this could change soon: expect most webkit-based browsers to catch up one by one over the next time. Especially developers for mobile platforms will benefit from more options in their arsenal, so they should listen carefully. I'll try to give a short overview of the current state of CSS 3D-Transformations in this mini-series. This first part is mainly about the basic CSS 3D-properties. In the second part I will talk about transformation matrixes. And in the last part we will learn about higher mathematics (Quaternions anybody?) and natural object rotation.

My DIVs in 3D???

The purpose of CSS 3D transformations is to allow the designer the manipulation of DOM-Objects not only in the plane (x, y, top, left, right, bottom), but in 3-D space (z) as well. You may think of this as some gimmick without substance but, used properly, it can add value. CSS-3D Transformations can, especially when used in conjunction with CSS-Transitions, help to structure Interfaces into different sections and make the transition between this sections more comprehensible.

What's more: I prefer having a lot of tools in my box. If a utility helps to enrich a user-experience it is welcome. In particular I'm thankful for every instrument that supports me in budgeting the precious commodity screen-estate on mobile devices.

The Situation

To be able to see the examples you will need a browser that is able to understand CSS 3D-transformations. Currently this are:

Unfortunately the current Nightly build of Webkit for Windows doesn't support CSS3D-Transformations. I can only recommend to check from time to time wether the functionality has changed.

As you can see, currently CSS 3D Transformations are of particular interest to developers who do HTML-apps for the iDevice-Platform.

Which Browsers will Support The Standard?

It's most likely other webkit-based browsers will be the first to catch up. Besides Apples Safari, Webkit is also the foundation for Google's Chrome. Webkit may be not very dominant on the desktop, but on smartphones it is the prevalent rendering-engine, although the difference between implementations can be substancial.

Step by Step Walkthrough:

Designers with a background in 3-D Animations should not have too high expectations: the standard doesn't know anything about light sources, cameras, or shaders. 3D-Navigation is very limited, as viewpoint-rotation is not possible. On the other hand: even designers who already have been involved into 3-D may find some of the concepts quite abstract and unintuitive (what are transformation-matrixes?) and the interaction of the 3D-Element and other elements on the page is not always feasible (how will floats behave? What are margins?).

Before we carry on, I recommend to play with this demo. You can manipulate the CSS-properties independently and watch the result in real-time. Hopefully this will give you a better understanding of the abstract subject.

Open Example

A side note: we can learn something about the disappointing SVG-implementation in Safari in this example: all background-images are svg, so you should expect them to be razorsharp all the time. Unfortunately this isn't the case, as Safari only uses a cached bitmap for distortion.

So let's start with our html-document:

<div id="container"> <div id="child"> </div> </div>

The next thing we want to do is to rotate, scale and reposition div#child. Before we can do this, we have to tell div#parent that its children now live in 3-D space (notice the vendor-specific prefix "-webkit-" prepended to all CSS-properties:

div#container{ -webkit-perspective: 250px; -webkit-perspective-origin: 50% 80%; }

Both declarations set the stage. None of them will cause any changes to the appearance of "parent". The only thing we do here is determine how children of "container" will be rendered.

The concept behind perspective is not very intuitive. Imagine a pyramid between the viewer and the z-plane. "perspective" would be the distance between the top of the pyramid and the z-plane. "Perspective" can be compared to the field viewing angle of your camera. The higher "perspective", the steeper the pyramid, so the transformed objects size will be nearer to it's untransformed size. A rule of thumb: values from 700 to 1000 will be recognized as "normal" and are a good starting-point.

"perspective-origin" determines the coordinates for the perspective-centers x- and y- values. It is like positioning a camera: "perspective" is the field-viewing-angle, "perspective-origin the x- and y-coordinates of the camera. Here we do use a percent-value, but absolute (px, cm, in, em etc..) or other relative (left, top, right, bottom, center) units would be allowed as well.

After setting the stage, we will now transform the child-element:

div#child{ -webkit-transform-origin: 50% 50% 50%; -webkit-transform: perspective(0) translate3d(50px, 40px, 80px) scale3d(1, 2, 0) rotate3d(0, 1, 0, 45deg); -webkit-transform-style: preserve-3d; }

transform-origin:

This is the center for the transformation. Units allowed are the same as for "perspective". Values for "z" are allowed, but didn't have any effect in my experiments.

transform: ...

Here we will group all transformations:

transform: perspective(val)

A kind of short-version of "perspective:val". This time it is not applied to the container but directly to the child. In contradiction to "pespective" it will alter the appearance of the object, not its children. If the container does have a "perspective" declaration, both values will multiply.

transform: translate3d(x, y, z):

Moves the object along the corresponding axis.

transform: scale3d(x, y, z)

Will scale the object along the corresponding axis. A value of 1 will preserve the original value. A need for scaling along the z-axis seems unnecessary first, as DOM-Elements usually do not have any depth. Anyway situations are possible where a z-scaling can be reasonable, for example if you arrange a group of divs in cube-form. This group could indeed be scaled z-wise.

transform: rotate3d(x-vektor, y-vektor, z-vektor, angle)

A rotation around a vector-axis. First we will determine a vector by setting its x, y, and z values. Its important to know that not the values themselves are important, but the relation of the values: rotate3d(5, 6, 10, 45deg) will give the same effect as rotate3d(50, 60, 100, 45 deg). The 4th value determines the angle of the rotation. Degrees(deg) and radian(rad) are allowed as units for the angle. I. e. rotate3d(0, 1, 0, 90deg) will rotate he object 90 degrees around the y-axis.

-webkit-transform-style:

One more CSS-property that will have only an effect on its children. The 2 possible values are "preserve-3d" and "flat" with "preserve-3d" being default.

There are some more transformations I didn't mention because I think they are fairly self-explaining:

So there's only transformation-matrix matrix3d(…) left, which I will discuss in part 2 of this series.

Trackback

20 Responses to “CSS 3D Transforms verstehen (CSS 3D – 1)Understanding CSS 3D Transforms (CSS 3D – 1)

  1. Comment by Webstandard-Blog 05/17/2010

    I really love the ne CSS3 Modules, but there will be a long way to go until all the major browser (including IE) support these features ;o(

  2. Comment by Alex Grande 06/29/2010

    Nice looking article. Great demo. Thanks!

  3. Comment by Benton 12/23/2010

    Brilliant!
    Thank you
    J

  4. Comment by H 02/22/2011

    You’ve talked about webkit, but have the other browsers expressed any interest in supporting this? Or is there no information either way?

  5. Comment by Dirk 02/23/2011

    A the moment only Webkit offers CSS3D transforms, even though I heard rumors that firefox wont to include them in a future release. The technology is still in it’s early stages and I wouldn’t recommend using it outside of IOs.

  6. Comment by Scott Gale 05/29/2011

    Thanks for writing this article. It helped when I was building out this coverflow using CSS 3D transforms: http://scottgale.com/blog/coverflow-css-3d-transforms/2011/05/24/

  7. Comment by Dirk 05/29/2011

    Hi Scott, great to hear that it was useful for you. And great demo too.

  8. Comment by David Gregg 08/29/2011

    My God man! :D All I want to know how to transform a DIV into a trapezoid! I just want a block of text to look like the top is bigger and wider than the bottom. Can someone give me a quick code snippet?

  9. Comment by Dirk 09/06/2011

    Hi David, right now this is only possible with css3d transfoms. Use something like “-webkit-transform: perspective(700) rotateZ(45deg);”. Anyway this is not a true irregular distortion but a perspective distortion. And it will only show up in supporting browsers.

  10. Comment by js 02/26/2012

    Thank you so much for creating and sharing this.

    Excellent !

  11. Pingback by Webdev | Pearltrees 03/15/2012

    […] Understanding CSS 3D Transforms 1 | eleqtriq Before we carry on, I recommend to play with this demo. […]

  12. Comment by jordanarseno 04/17/2012

    Excellent tutorial. Thanks dude!

  13. Trackback by San Diego Web Design 04/18/2012

    san diego web design company…

    Thanks for the great post, I have linked back to your site here. http://www.arselin.com/sites-we-like/ Thanks for the great article….

  14. Comment by Ivo 04/24/2012

    Hey, we don’t really need to wait for all browsers to comply with standards – see, all apple devices already and always will support the standard to the fullest extend because they use a very consistent modern standard. If their market share keeps growing the same way just another year or so – we would be doing well, developing just for that premiere platform worldwide. People are hungry for the best web experience possible and won’t tolerate collective compromises much longer. Go express yourself within the iOS and you’ll be rewarded instantly (check Solar Walk by Vito Technology Inc. for inspiration – http://itunes.apple.com/us/app/solar-walk-3d-solar-system/id347546771?mt=8)

  15. Pingback by Adventures In The Third Dimension: CSS 3D Transforms | Smashing Coding 04/28/2012

    […] complicated; the length is like a distance between you and the object that you’re viewing (a tutorial on Eleqtriq has a more technical explanation and diagram). For our purposes, you just need to know that the […]

  16. Pingback by הטרנדים החמים ב-CSS3 | Newsgeek 06/21/2012

    […] שמסביר על הבסיס של השימוש בטכנולוגיה המשיכו לקרוא כאן. ולמי שרוצה להתעמק בנושא הפרספקטיבה הנה מאמר מצוין עם […]

  17. Pingback by GNC Designstudio 06/23/2012

    […] Link: Understanding CSS 3D Transforms […]

  18. Pingback by 20 exemplos extraordinários de CSS 3D « wiliamluis 09/04/2012

    […] seu artigo Entendimento CSS 3D Dirk Weber explica os passos necessários para criar algo com transformações 3D. Com uma […]

  19. Pingback by CSS3 Dönüştürme(Transforms) ve 3B Dönüştürme / Fatih Hayrioğlu'nun not defteri 09/11/2012
  20. Pingback by 开发者的福音 CSS 3D转换教程大放送 – 90互联网数据中心 09/26/2012

    […] 2. Understanding CSS 3D Transform […]