Skip to main content

the avatar of Aleksa Sarai

umoci: a New Tool for OCI Images

Very recently, I've been working on implementing the required tooling for creating and modifying Open Container Initiative images without needing any external components. The tool I've written is called umoci and is probably one of the more exciting things I've worked on in the past couple of months. In particular, the applications of umoci when it comes to SUSE tooling like the Open Build Service or KIWI is what really makes it exciting.

a silhouette of a person's head and shoulders, used as a default avatar

Testing the untestable

Admit it: how many times you have seen “software from this branch is completely untested, use it at your own risk” when you checked the latest code from any FOSS project? I bet you have, many times. For any reasonably modern project, this is not entirely true: Continuous Integration and automated testing are a huge help in ensuring that the code builds and at least does what it is supposed to do. KDE is no exception to this, thanks to build.kde.org and a growing number of unit tests.

Is it enough?

This however does not count functional testing, i.e. checking whether the software actually does what it should. You wouldn’t want KMail to send kitten pictures as a reply to a meeting invitation from your boss, for example, or you might want to test that your office suite starts and is able to actually save documents without crashing. This is something you can’t test with traditional unit testing frameworks.

Why does this matter to KDE? Nowadays, the dream of always summer in trunk as proposed 8 years ago is getting closer, and there are several ways to run KDE software directly from git. However, except for the above strategy, there is no additional testing done.

Or, should I rather say, there wasn’t.

Our savior, openQA

Those who use openSUSE Tumbleweed know that even if it is technically a “rolling release” distribution, it is extensively tested. That is made possible by openQA, which runs a full series of automated functional tests, from installation to actual use of the desktops shipped by the distribution. The recently released openSUSE Leap has also benefited from this testing during the development phase.

“But, Luca,” you would say, “we already know about all this stuff.”

Indeed, this is not news. But the big news is that, thanks mainly to the efforts of Fabian Vogt and Oliver Kurz, now openQA is testing also KDE software from git! This works by feeding the Argon (Leap based) and Krypton (Tumbleweed based) live media, which are roughly built daily, to openQA, and running a series of specific tests.

You can see here an example for Argon and an example for Krypton (note: some links may become dead as tests are cleaned up, and will be adjusted accordingly). openQA tests both the distro-level stuff (the console test) and KDE specific operations (the X11 test). In the latter case, it tests the ability to launch a terminal, running a number of programs (Kate, Kontact, and a few others) and does some very basic tests with Plasma as well.

Is it enough to test the full experience of KDE software? No, but this is a good solid foundation for more automated testing to spot functional regressions: during the openSUSE Leap 42.2 development cycle, openQA found several upstream issues in Plasma which were then communicated to the developers and promptly fixed.

Is this enough for everything?

Of course not. Automated testing only gets so much, so this is not an excuse for being lazy and not filing those reports. Also, since the tests run in a VM, they won’t be able to catch some issues that only occur on real hardware (multiscreen, compositing). But is surely a good start to ensure that at least obvious regressions are found before the code is actually shipped to distributions and then to end users.

What needs to be done? More tests, of course. In particular, Plasma regression tests (handling applets, etc.) would be likely needed. But as they say, every journey starts with the first step.

the avatar of Jos Poortvliet

3 alternative reasons why you should test Nextcloud 11 Beta

On the Nextcloud blog I just published about the beta for Nextcloud 11. The release will deliver many improvements and is worth checking out in itself, plus I put a nice clickbait-style title and gave three reasons to test it.

But I actually have some more reasons to test. You see, Nextcloud is one of the tools we need to keep our democracy working. As Frank notes on his home page:
"Privacy is the foundation of democracy"
And he is completely right. So, here are three different reasons why you should test (and help improve) Nextcloud:

1. The USA is making a massive swing towards even more spying

Obama has done nothing to curb the growth of the NSA and the scope of its operations. Secret laws spiked under his watch. Many of the folks about to be put in power by President-elect Trump favor more spying, including on US citizens, expansion of the NSA, a crackdown on whistleblowers and more. Trump's pick for CIA director calls for Snowden's execution. For what I can only guess must be giving proof of illegal government spying to dangerous terrorists like the Washington Post and the Guardian, who proceeded to win a Pulitzer prize by disclosing this information irresponsibly to the US public.

In general, as somebody who changes his stance on hugely important and complicated issues like torture in under an hour, it is impossible to predict what Trump will do with the most powerful spying agency in the world under his control, but his appreciation for dictatorial figures like Kim Jong Il and Putin gives plenty cause for concern.

2. Britain isn't doing much better

I wrote about the Snoopers' charter just some days ago - this piece of legislation goes further than any earlier piece of spying law. It allows not only passive spying but also actively hacking devices from citizens.

3. Nor is Europe

The UK is not alone. Since Snowden, Europe has complained a bit about the NSA but seems to simply follow suit, rather than doing anything about it. Germany is even introducing a bill that will allow spying on foreign journalists.

Help out!

So, how can you help? Well, test Nextcloud 11 Beta, obviously. Help others to use it, get them involved. But it goes beyond Nextcloud - promote the use of and help improve tools like Tor, Signal and others, or democracy is screwed.

Edit: updated the blog 

a silhouette of a person's head and shoulders, used as a default avatar

Watching org.libelektra with Qt

libelektra is a configuration library and tools set. It provides very many capabilities. Here I’d like to show how to observe data model changes from key/value manipulations outside of the actual application inside a user desktop. libelektra broadcasts changes as D-Bus messages. The Oyranos projects will use this method to sync the settings views of GUI’s, like qcmsevents, Synnefo and KDE’s KolorManager with libOyranos and it’s CLI tools in the next release.

Here a small example for connecting the org.libelektra interface over the QDBusConnection class with a class callback function:

Declare a callback function in your Qt class header:

public slots:
 void configChanged( QString msg );

Add the QtDBus API in your sources:

#include <QtDBus/QtDBus>

Wire the org.libelektra intereface to your callback in e.g. your Qt classes constructor:

if( QDBusConnection::sessionBus().connect( QString(), "/org/libelektra/configuration", "org.libelektra", QString(),
 this, SLOT( configChanged( QString ) )) )
 fprintf(stderr, "=================== Done connect\n" );

In your callback arrive the org.libelektra signals:

void Synnefo::configChanged( QString msg )
{
 fprintf( stdout, "config changed: %s\n", msg.toLocal8Bit().data() );
};

As the number of messages are not always known, it is useful to take the first message as a ping and update with a small timeout. Here a more practical code elaboration example:

// init a gate keeper in the class constructor:
acceptDBusUpdate = true;

void Synnefo::configChanged( QString msg )
{
  // allow the first message to ping
  if(acceptDBusUpdate == false) return;
  // block more messages
  acceptDBusUpdate = false;

  // update the view slightly later and avoid trouble
  QTimer::singleShot(250, this, SLOT( update() ));
};

void Synnefo::update()
{
  // clear the Oyranos settings cache (Oyranos CMS specific)
  oyGetPersistentStrings( NULL );

  // the data model reading from libelektra and GUI update
  // code ...

  // open the door for more messages to come
  acceptDBusUpdate = true;
}

The above code works for both Qt4 and Qt5.

the avatar of Jos Poortvliet

Brittain’s Snoopers charter threatens your privacy

pic from the ZDNet article
The United Kingdom this week passed the so called Snoopers Charter, a law which forces UK internet providers to store the browsing history of UK citizens for a full year. You, your family, visitors or any devices in your household which have been hacked (the government is now allowed to do that, by the way) better not visit anything bad as the government can get their hands on this data quite easily. What does this mean and what can you do?

An attack on privacy

There is a global siege on privacy. Governments all over the world have introduced legislation (sometimes secret) which forces email, internet or data storage providers to track what you do and make that data available to their governments. This, of course, also means third parties who gain access to the storage systems can see and abuse it. And because so many of us have put so much of our data at just a few providers, we're at great risk as events like last week's shutdown of hundreds of Google accounts did show.

While Google, Dropbox and others lure customers in with 'free' data storage and great online services, governments benefit from centralized data storages as it makes it easy for them to hack in or demand data from these companies.

Why this surveillance?

While governments usually claim they need access to this data to find terrorists or child pornography, experts point out that it will not be helpful at all. As multiple experts (even internally) put it, growing the haystack makes it harder to find the needle. Intelligence agencies are swamped with data and nearly every terrorist attack in western states over the last decade took place despite the agencies having all information they would have needed to prevent it. The Paris attackers, for example, coordinated their attack using plain SMS messages. The Guardian thus rightly points out that:
"Paris is being used to justify agendas that had nothing to do with the attack"
which has become a familiar refrain after nearly every terrorist attack.

Indeed, we all know the argument But you have nothing to hide, do you? and indeed, we probably don't. But some people do, so they'll try to avoid being seen. That being illegal won't change their behavior...

And as Phill Zimmermann, the inventor of the PGP encryption pointed out:
"When privacy is outlawed, only outlaws will have privacy"

So not terrorists. Then what?

Experts agree that the vast majority of these surveillance and anti-privacy laws have little or no effect on real criminals. The crime syndicates, corrupt politicians and large corporations evading taxes and anti-trust/health/environmental laws, they DO have something to hide, and thus they would use encryption or avoid surveilled communication methods even if it were outlawed.

However, ordinary citizens, including grass-roots local activists, charitable organizations, journalists and others, who DO have nothing to hide, would be surveilled closely. And with that information, the real criminals mentioned earlier - crime syndicates, corporations or corrupt politicians - would have weapons in hand to keep these citizens from bothering them. Whistle blowers can be found out and killed (like in Mexico), journalists can be harassed and charged for trivial transgressions (like was recently done at the US pipeline protest) and charities can be extorted.

What can we do?

Luckily, there are initiatives like the Stanford Law Schools' Crypto Policy Project which aim to train, for example, journalists in the use of encryption. Tools and initiatives like Signal, PGP email encryption, Let's Encrypt and Nextcloud provide the ability for users to protect themselves and their loved ones from surveillance. More importantly, these at the same time making it harder and more costly to conduct mass surveillance.

There is nothing wrong with governments targeting criminals with surveillance but just vacuuming up all data of all citizens that might, some day, be used is a massive risk for our democracy. We all have a responsibility to decentralize and use tools to protect our privacy so those who need it (press, activists and others) have a place to hide.

a silhouette of a person's head and shoulders, used as a default avatar

openSUSE Leap 42.2 est sortie !

openSUSE Leap 42.2 est sortie le 16 novembre dernier. C’est la deuxième version qui porte le nom de Leap. Cette dénomination rappelle le changement opéré l’an dernier dans la façon de construire la distribution : le cœur du système – noyau, système d’init, … – est celui de SLE, la distribution commerciale de SUSE.

L’aspect communautaire reste fort cependant, des centaines de logiciels étant ajoutés par dessus cette base, par des caméléons de tous bords. En ce sens, Leap 42.2 est un exemple : 1400 nouveaux paquets ont été incorporés et surtout le nouveau bureau KDE Plasma 5.8 LTS a été intégré, entièrement par la communauté.

Logo d'openSUSE Leap

Note : cette dépêche a été réalisée par AR7 sur le site de linuxfr.org, sous licence CC by-sa, elle s’inspire librement de l’annonce de sortie officielle.

En bref

Si l’on devait résumer cette nouvelle version en quatre points-clés, on pourrait dire qu’openSUSE Leap 42.2 est…

Encore un peu plus orientée entreprise

Peluche caméléon SUSE

C’est vrai.

openSUSE Leap est basée sur SLE (SUSE Linux Enterprise), la distribution commerciale de SUSE. La version 42.2 de Leap partage encore plus de code source avec SLE, en l’occurrence avec sa version 12 SP 2.

Des technologies comme NVDIMM, OmniPATH et DPDK avec Open vSwitch sont maintenant prises en charge. Xen ne requiert plus son propre noyau et est supporté par le noyau par défaut.

En même temps que la base de code de SLE, openSUSE Leap 42.2 reçoit les paquets, la maintenance et les correctifs de la communauté openSUSE et des ingénieurs de SUSE. La série 42 de Leap est officiellement prise en charge pour au moins 36 mois à compter de la version 42.1, c’est-à-dire jusqu’en novembre 2018. Cela inclut des mises à jour de maintenance et de sécurité.

Prête pour les serveurs

Network

openSUSE Leap 42.2 est la première version de Leap à offrir un profil « Serveur » durant l’installation. Lancer une plate-forme web ou mail est plus facile, tout comme gérer des projets plus complexes utilisant la virtualisation ou des technologies à base de conteneurs.

Il est aussi bon de rappeler que Leap et toutes les autres distributions openSUSE proposent un installateur complet en mode texte, donnant les mêmes fonctionnalités que l’installateur graphique sans pour autant utiliser X. Cet installateur est aussi capable de faire des installations à distance en utilisant VNC ou SSH, permettant ainsi de mettre en place openSUSE Leap sur un serveur sans accès physique.

Folle de Konqi !

Konqi, la mascotte de KDE

Konqi, le petit dragon vert de KDE est de retour et en pleine forme ! Plasma 5.8 donne une nouvelle dimension à openSUSE Leap. Cette version du bureau KDE, estampillée LTS, devrait plaire aux utilisateurs soucieux de stabilité. Combiné avec Qt 5.6 et KDE Frameworks 5.26, Plasma 5.8 apporte aux utilisateurs de Leap 42.2 stabilité et fiabilité.

Amatrice de noyau LTS

Tux

Le noyau Linux 4.4 LTS pour openSUSE Leap 42.2 améliore les performances et les fonctionnalités du systèmes de fichiers Btrfs, avec notamment un nouveau « filtre d’équilibrage » ( balance filter). La para-virtualisation est activée dans le noyau par défaut. Ce noyau améliore la cryptographie ainsi que le support du standard TPM (Trusted Platform Module) version 2.0 et la virtualisation imbriquée via KVM.

En détails

Pour les utilisateurs

KDE

Bureau KDE Plasma 5.8

openSUSE Leap 42.2 est donc la première distribution à offrir le bureau Plasma LTS du projet KDE. L’environnement par défaut est en effet Plasma 5.8, riche en fonctionnalités et offrant de bonnes performances. Les utilisateurs de KDE qui étaient passés à autre chose devraient réévaluer cette version qui apporte des améliorations majeures en terme de stabilité et de fonctionnalités.

KRunner n’ouvre plus seulement des applications ; il peut aussi lancer certaines actions quand l’application démarre : ce sont les Jump List Actions.

La prise en charge du glisser-déposer a été ajouté pour apporter des résultats de recherche à n’importe quelle application.

Les utilisateurs de smartphones sous Android peuvent obtenir l’intégration de leur appareil avec l’application KDE Connect (disponible sur Google Play). Elle permet aux utilisateurs de recevoir des SMS sur leur poste de travail ou transférer des fichiers vers leur téléphone. Pour que ça marche, il ne faut pas oublier d’autoriser le service KDE Connect dans le module pare-feu de YaST.

Enfin, les administrateurs système apprécieront le support de Kiosk. permettant de fixer et déployer des profils de bureau.

GNOME

Bureau GNOME 3.20

GNOME 3.20 offre aux utilisateurs de nouveaux contrôles de vie privée, notamment la possibilité d’autoriser la géolocalisation par application, un accès aux contrôles multimédia directement depuis la zone notification/date/calendrier et une nouvelle fenêtre listant les différents raccourcis clavier et gestes disponibles. Cette dernière peut être ouverte dans la plupart des applications GNOME, depuis le menu ou en utilisant le raccourci Ctrl+? ou Ctrl+F1. GNOME permet également accéder à Google Drive directement depuis l’application Fichiers.

Grâce à près de 870 contributeurs, plus de 28000 changements ont eu lieu depuis la version précédente. Tous les détails dans les notes de version de GNOME 3.20.

Autres bureaux

Bureau LXQt 0.11.0 en action sur openSUSE Leap 42.2

openSUSE Leap 42.2 offre à ses utilisateurs la possibilité de choisir d’autres bureaux. Vous pouvez essayer par exemple Xfce, Enlightenment, MATE, Cinnamon et LXQt. Seuls Xfce et Enlightenment sont disponibles sur l’image DVD d’installation ; il sont cependant tous disponibles en ajoutant les dépôts en ligne ou en utilisant l’image d’installation par le réseau.

LXQt 0.11.0, dont l’expérience utilisateur a été grandement améliorée grâce à la correction de nombreux bogues, introduit pavucontrol-Qt, le port Qt de pavucontrol, le mixer PulseAudio basé sur GTK.

Pour les administrateurs système

Virtualisation

Installation des outils KVM avec YaST

openSUSE est une plateforme relativement complète pour faire de la virtualisation. On retrouve notamment QEMU 2.6.1, VirtualBox 5.0, GNOME Boxes 3.20, Xen et KVM ainsi que des solutions à base de conteneurs comme Docker et LXC. Une partie de la configuration peut se faire avec YaST, permettant de déployer des solutions plus rapidement et plus facilement.

YaST

L'âne de YaST

Les sprints de l’équipe YaST menés jusqu’à la sortie de Leap 42.2 ont apporté pas mal de bonnes choses et ont rendu YaST (un peu) plus intuitif. La communauté YaST a remodelé l’interface utilisateur pour améliorer l’utilisabilité et continue d’ajouter de nouveaux outils et modules, après qu’ils ont fait leurs preuves dans Tumbleweed.

yast2-alternatives est un nouveau module, créé lors du GSoC 2016, pour gérer le système d’alternatives d’openSUSE (issu de Debian). Un autre module, yast2-vpn, permet de configurer des passerelles et des clients VPN. yast2-auth-client, qui permet de configurer un système d’authentification centralisé, a été presque complètement réécrit. La gestion du chargeur d’amorçage a été améliorée pour élargir le support du Trusted Boot et la configuration de la protection du mot de passe a été refaite au propre. yast2-firewall supporte maintenant firewalld, en plus du vénérable SuSEFirewall2.

En cas d’incident lors de l’installation, il est maintenant possible de lancer un débogueur. Les utilisateurs ayant une connaissance Ruby peuvent l’utiliser pour tracer ce qui s’est passé et trouver une solution voire un contournement.

L’impact sur la mémoire vive a été considérablement réduit, et la configuration du clavier et des polices de caractère de la console a été adaptée pour une meilleure compatibilité avec systemd.

Gestion des systèmes

Module snapper de YaST

Snapper peut maintenant utiliser les quotas Btrfs pour gérer le nettoyage des instantanés. Fini les partitions racines saturées à cause d’un trop grand nombre de snapshots !

openSUSE Leap dispose de Samba 4.4.2, qui fonctionne mieux avec les domaines Windows 2003.

systemd 228 apporte un changement notable au niveau des fichiers temporaires : les attributs v, q et Q créeront désormais de simples répertoires même sous Btrfs (pas de sous-volume), si le répertoire racine est un simple répertoire. Cela devrait simplifier les choses avec certains environnements chroot qui ne connaissent pas le concept de sous-volume Btrfs.

La version d’AppStream améliore l’interaction avec les dépôts de logiciels.

La version de MariaDB ne bouge pas par rapport à la 42.1 et la petite mise à jour de MySQL vers la version 5.1.35 résout plusieurs soucis touchant le basculement vers un système de secours (failover).

Rappelons qu’openSUSE Leap utilise des Delta RPM pour les mises à jour de maintenance, réduisant l’impact sur la bande-passante.

Pour les développeurs

EDI et outillage

Capture d'écran de KDevelop 5.0.1

Avec le bureau KDE vient KDevelop 5.0.1.

Une version mûre du Qt 5 GUI Toolkit, la 5.6, est incluse dans Leap 42.2. On recense plus de 800 améliorations depuis la version présente dans openSUSE Leap 42.1. Qt 5.6 est une version LTS et apporte des corrections de sécurité dans le framework Qt ainsi que dans des bibliothèques tierces.

GTK 3.20, partagé avec SLE 12 SP2, fournit un toolkit solide et stable pour construire des applications. GNOME Builder est disponible en tant qu’EDI et permet non seulement de coder des applications GTK en C, C++ et Vala mais aussi de réaliser des projets dans de nombreux autres langages.

Pour tous vos besoin en compilation, Leap 42.2 contient GCC 4.8.5, 5.3.1 et 6.1.1. LLVM/Clang 3.8.0 est également disponible. CMake 3.5 est aussi de la partie, en fournissant un environnement de construction puissant et multi-plateforme pour les développeurs de projets Open-Source.

Enfin, niveau cryptographie, la version d’OpenSSL que l’on retrouve dans Leap 42.2 est la 1.0.2h, qui modifie le comportement d’ALPN et empêche ASN.1 BIO de faire des allocations mémoire excessives. OpenSSH est à la version 7.2p2 et assainit les informations d’identification pour X11.

Langages et bibliothèques

Parmi les langages de programmation présents dans openSUSE Leap 42.2, on retrouve notamment Python 2.7, Ruby 2.1 et Perl 5.18.

Cette version de Leap fournit également de nouvelles versions majeures pour libvirt (2.0) et libzypp (16.2).

Leap dispose d’une glibc 2.22 bien établie ainsi que de libsigc++ 2.8.

En plus

Images d’installation

Icône de téléchargement

Si vous voulez installer openSUSE Leap 42.2, rendez-vous sur software.opensuse.org/422. À noter que l’architecture i586 n’est plus disponible depuis Leap 42.1.

Des ports sont disponibles pour les architectures ARM et PowerPC.

Enfin, il est tout à fait possible de mettre à niveau une installation de Leap 42.1 vers Leap 42.2 en utilisant la commande zypper dup. N’oubliez pas alors de lire les notes de version par rapport aux paquets supprimés ou renommés depuis la version 42.1.

Pour les contributeurs

Logo de Weblate

Leap 42.2 est la première version d’openSUSE (en dehors de Tumbleweed) à utiliser Weblate pour gérer la traduction du système dans plus de 50 langues. Cette application web permet à tous, du traducteur professionnel au contributeur occasionnel, de prendre part au processus et rend possible la fusion des traductions d’openSUSE avec celles de SLE.

Logo d'openQA

Un autre outil qui est de plus en plus utilisé par openSUSE est openQA, un logiciel pour tester des systèmes d’exploitation en faisant de la comparaison de captures d’écran. Il est également utilisé par Fedora.

Logo d'Open Build Service

Enfin, l’outil le plus connu et le plus utilisé est l’Open Build Service, un système permettant de construire des paquets RPM, deb et autres de façon automatisée. À noter que le projet openSUSE est impliqué, tout comme bien d’autres distributions, à rendre reproductibles la compilation et l’empaquetage des logiciels qu’elle distribue.

Tumbleweed

Logo d'openSUSE Tumbleweed

Si Leap se porte bien, Tumbleweed, la distribution en rolling release du projet openSUSE, est en pleine forme. L’important travail d’intégration en amont de chaque nouveau snapshot permet d’éviter beaucoup de régressions. Et, sur le long-terme, c’est aussi openSUSE Leap qui bénéficie de ces efforts… juste quelques mois plus tard !

Note : cette dépêche a été réalisée par AR7 sur le site de linuxfr.org, sous licence CC by-sa, elle s’inspire librement de l’annonce de sortie officielle.

a silhouette of a person's head and shoulders, used as a default avatar

Details zu Migration und Zukunftsplänen

In meinem letzten Post versprach ich mehr Details über die Migration der crowbyte.org webseite und des Blogs, sowie mehr zu meinen Plänen für die Zukunft, zu verraten und halte mit diesem Post nun mein Versprechen.

Migrationsdetails

Nach über einem halben Jahr der Abwesenheit, hatte ich die Zeit und Gelegenheit die Richtung der Webseite und des Blogs noch einmal grundlegend zu überdenken.

Bisher nutzte ich Nikola als Seitengenerator für den Blog und die Webseiten. Dies war eine wohl übe...

a silhouette of a person's head and shoulders, used as a default avatar

Details on website migration and plans for the future

With my last post I promised to give some more detailed information on the migration of the crowbyte website and blog as well as my plans for the future of crowbyte.org and I live up with my promise in this post.

Migration details

After over half a year of absence I had the time to rethink the direction into which the blog and website headed lately.

I used Nikola as a page generator for my blog and websites. This was a decision which I made after a lot of consideration and testing of av...

a silhouette of a person's head and shoulders, used as a default avatar

Linux did not win, yet

http://www.cio.com/article/3141918/linux/linux-has-won-microsoft-joins-the-linux-foundation.html Yes, Linux won on servers. Unfortunately... servers are not that important, and Linux still did not win on desktops (and is not much closer now than it was in 1998, AFAICT). We kind-of won on phones, but are not getting any benefits from that. Android is incompatible with X applications. Kernels on phones are so patched that updating kernel on phone is impossible... . This means that Microsoft sponsors Linux Foundation. Well, nice, but not a big deal. Has Microsoft promised not to use their patents against Linux? Does their kernel actually contain vfat code? Can I even get source for "their" Linux kernel? [Searching for Linux on microsoft.com does not reveal anything interesting; might be switching to english would help...]
a silhouette of a person's head and shoulders, used as a default avatar

Responsive HTML with CSS and Javscript

In this article you can learn how to make a minimalist web page readable on different format readers like larger desktop screens and handhelds. The ingredients are HTML, with CSS and few JavaScript. The goals for my home page are:

  • most of the layout resides in CSS in a stateless way
  • minimal JavaScript
  • on small displays – single column layout
  • on wide format displays – division of text in columns
  • count of columns adapts to browser window width or screen size
  • combine with markdown

CSS:

h1,h2,h3 {
  font-weight: bold;
  font-style: normal;
}

@media (min-width: 1000px) {
  .tiles {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    align-items: flex-start;
    width: 100%;
  }
  .tile {
    flex: 0 1 49%;
  }
  .tile2 {
    flex: 1 280px
  }
  h1,h2,h3 {
    font-weight: normal;
  }
}
@media (min-width: 1200px) {
  @supports ( display: flex ) {
    .tile {
      flex: 0 1 24%;
    }
  }
}

The content in class=”tile” is shown as one column up to 4 columns. tile2 has a fixed with and picks its column count by itself. All flex boxes behave like one normal column. With @media (min-width: 1000px) { a bigger screen is assumed. Very likely there is a overlapping width for bigger handhelds, tablets and smaller laptops. But the layout works reasonable and performs well on shrinking the web browser on a desktop or viewing fullscreen and is well readable. Expressing all tile stuff in flex: syntax helps keeping compatibility with non flex supporting layout engines like in e.g. dillo.

For reading on High-DPI monitors on small it is essential to set font size properly. Update: Google and Mozilla recommend a meta “viewport” tag to signal browsers, that they are prepared to handle scaling properly. No JavaScript is needed for that.

<meta name="viewport" content="width=device-width, initial-scale=1.0">

[Outdated: I found no way to do that in CSS so far. JavaScript:]

function make_responsive () {
  if( typeof screen != "undefined" ) {
    var fontSize = "1rem";
    if( screen.width < 400 ) {
      fontSize = "2rem";
    }
    else if( screen.width < 720 ) {
      fontSize = "1.5rem";
    }
    else if( screen.width < 1320 ) {
      fontSize = "1rem";
    }
    if( typeof document.children === "object" ) {
      var obj = document.children[0]; // html node
      obj.style["font-size"] = fontSize;
    } else if( typeof document.body != "undefined" ) {
      document.body.style.fontSize = fontSize;
    }
  }
}
document.addEventListener( "DOMContentLoaded", make_responsive, false );
window.addEventListener( "orientationchange", make_responsive, false );

[The above JavaScript checks carefully if various browser attributes and scales the font size to compensate for small screens and make it readable.]

The above method works in all tested browsers (FireFox, Chrome, Konqueror, IE) beside dillo and on all platforms (Linux/KDE, Android, WP8.1). The meta tag method works as well better for printing.

Below some markdown to illustrate the approach.

HTML:

<div class="tiles">
<div class="tile"> My first text goes here. </div>
<div class="tile"> Second text goes here. </div>
<div class="tile"> Third text goes here. </div>
<div class="tile"> Fourth text goes here. </div>
</div>

In my previous articles you can read about using CSS3 for Translation and Web Open Font Format (WOFF) for Web Documents.