Tag Archiv: php
Making pretty, responsive, headers is always a tricky process. Until now you needed to use floats or other complicated tricks and you even had to manually adjust pixel values. But not any more!
The technique we are about to show you relies on the powerful flexbox layout mode to do all the dirty work for you. It uses just a handful of CSS properties to create a header that is properly aligned and looks good on all screen sizes, while leaving the code cleaner and less hacky.
The Technique
In our demonstrative example we’ve built a header, which is separated in three sections with typical header content nested within them:
- Left section – The company logo.
- Middle section – Various hyperlinks.
- Right section – A button.
Below you can check out a simplified version of the code.
In the first tab is the HTML where we group the sections in separate div tags. This makes it easier for CSS rules to be applied and generally produces a more organised code.
In the other tab is the CSS, which is just a couple of lines, does the entire job of finding the right places for the each of the sections.
Click the Run button to open up a live demo. You can test the responsiveness by resizing the frame:
<header>
<div class="header-left">CoolLogo</div>
<div class="header-center">
<ul>
<li><a href="#">Our products</a></li>
<li><a href="#">Pricing</a></li>
<li><a href="#">Blog</a></li>
</ul>
</div>
<div class="header-right"><button>Buy now</button></div>
</header>
header{
/* Enable flex mode. */
display: flex;
/* Spread out the elements inside the header. */
justify-content: space-between;
/* Align items vertically in the center. */
align-items: center;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Easiest Way To Make Responsive Headers</title>
<link href='https://fonts.googleapis.com/css?family=Fugaz+One' rel='stylesheet' type='text/css'>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
font: normal 16px sans-serif;
padding: 0 10%;
background: #eee;
}
body .container{
max-width:1200px;
margin:0 auto;
}
/* Header */
header{
/* Enable flex mode. */
display: flex;
/* Spread out the elements inside the header. */
justify-content: space-between;
/* Align items vertically in the center. */
align-items: center;
padding: 40px 100px;
color: #fff;
background-color: #488EAD;
}
.header-left{
font: normal 28px 'Fugaz One', cursive;
}
.header-left span{
color: #EAD314;
}
.header-center ul{
list-style: none;
}
.header-center ul li{
display: inline-block;
margin: 0 15px;
}
.header-center ul li a{
text-decoration: none;
color: #fff;
cursor: pointer;
font-weight: bold;
}
.header-right button{
color: #fff;
cursor: pointer;
font-weight: 800;
text-transform: uppercase;
padding: 12px 30px;
border: 2px solid #FFFFFF;
border-radius: 4px;
background-color: transparent;
}
.header-right button:hover {
background-color: rgba(255,255,255,0.1);
}
/* Main content */
.main-content{
padding: 60px 100px;
background-color: #fff;
line-height: 1.5;
color: #444;
}
.main-content h2{
margin-bottom: 38px;
}
.main-content p{
margin: 30px 0;
}
.main-content .placeholder{
margin: 40px 0;
height:380px;
background-color: #e3e3e3;
}
/* Media queries */
@media (max-width: 1200px){
header{
padding: 40px 60px;
}
.main-content{
padding: 100px 60px;
}
body {
padding: 0 5%;
}
}
@media (max-width: 1000px){
header{
/* Reverse the axis of the header, making it vertical. */
flex-direction: column;
/* Align items to the begining (the left) of the header. */
align-items: flex-start;
}
header > div{
margin: 12px 0;
}
.header-center ul li{
margin: 0 15px 0 0;
}
}
@media (max-width: 600px){
body {
padding: 0 10px;
}
.header-left{
margin-top:0;
}
header {
padding: 30px;
}
.main-content{
padding:30px;
}
}
</style>
</head>
<body>
<div class="container">
<header>
<div class="header-left"><span>Cool</span>Logo</div>
<div class="header-center">
<ul>
<li><a href="#">Our products</a></li>
<li><a href="#">Pricing</a></li>
<li><a href="#">Blog</a></li>
</ul>
</div>
<div class="header-right"><button>Buy now</button></div>
</header>
<section class="main-content">
<h2>Header with three justify aligned sections</h2>
<p>Using the power of flexbox, the logo, links, and button of our header stay in their designated places, no matter the screen size. The <strong style="white-space: nowrap;">justify-content</strong> property offers a clean approach and allows us to align the section of the header without a hassle. No need for any floats, margins or crazy width calculations.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus at congue urna, pellentesque faucibus justo. Integer a lorem a mauris suscipit congue luctus ut quam. Mauris pellentesque pellentesque mattis. In sed mi dignissim, faucibus elit at, rutrum odio. Mauris et velit magna. Maecenas iaculis eget sapien eu gravida. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vestibulum a egestas magna. Aenean tellus elit, aliquet at lacinia at, accumsan eget neque. Maecenas rutrum risus quis sem scelerisque sagittis. Quisque sit amet turpis lorem. </p>
<div class="placeholder"></div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus at congue urna, pellentesque faucibus justo. Integer a lorem a mauris suscipit congue luctus ut quam. Mauris pellentesque pellentesque mattis. In sed mi dignissim, faucibus elit at, rutrum odio. Mauris et velit magna. Maecenas iaculis eget sapien eu gravida. Interdum et malesuada fames ac ante ipsum primis in faucibus. Vestibulum a egestas magna. Aenean tellus elit, aliquet at lacinia at, accumsan eget neque. Maecenas rutrum risus quis sem scelerisque sagittis. Quisque sit amet turpis lorem. </p>
</section>
</div>
</body>
</html>
Full responsiveness
The space-between
trick will always take care of the alignment, even when the screen size changes. However, when the viewport becomes too small for a horizontal header, we can make it go vertical by changing the flex-direction
property in a media query.
@media (max-width: 1000px){
header{
/* Reverse the axis of the header, making it vertical. */
flex-direction: column;
/* Align items to the begining (the left) of the header. */
align-items: flex-start;
}
}
Conclusion
This sums up our quick tutorial! We hope you found it useful and will start applying it right away. Flexbox has pretty good browser support nowadays, so unless your user base is IE heavy, this technique can be applied without causing any mayhem.
To learn more about flexbox and the CSS properties that we used, check out these links:
Every web developer should know SQL. Although it has been around since the 70s, it is still widely used, and you can’t build a serious application without it. Most full-stack frameworks have libraries for dealing with the SQL complexity – ActiveRecord, Doctrine, Hibernate and more. But often times you need to get your hands dirty and write low-level SQL.
This is why we’ve prepared a short and to-the-point introduction to the basics of SQL. Within the article, you will find our interactive editors for writing and executing your code. Don’t be afraid to experiment with them and try to complete the bonus tasks.
Let’s begin!
1. Create Table
When creating new tables in SQL the CREATE TABLE
statement is called. It expects as it’s arguments all the columns we want in the table, as well as the their data types.
Here we are creating a simple table called months. It consists of 3 columns:
- id – The number of the month in the calendar year (integer).
- name – Name of the month (string, maximum of 10 characters).
- days – The number of days in that month (integer).
And this is how the respective SQL looks like:
CREATE TABLE months (id int, name varchar(10), days int);
Also when creating tables, it’s advisable to add a primary key to one of the columns. It will help keep entries unique and will speed up select queries. We won’t be covering them in this lesson but you can read about them here.
2. Insert Rows
Now let’s populate months with a few rows of information. Adding entries to a table is done via the INSERT
statement. There are two different ways to use it:
The first way does not specify the column names where the data will be inserted, it only expects the values and leaves it up to the developer to provide all the data in the correct order.
INSERT INTO months VALUES (1,'January',31);
The above is shorter, but there is a major issue – if we add additional columns in the future, the query will break. The preferred way to write this is to include the columns:
INSERT INTO months (id,name,days) VALUES (2,'February',29);
You can try running these commands in the editor below.
Bonus: Write an INSERT
statement to add more months to the table.
3. Select
Select queries are our best friend when we want to fetch data from the database. They are used all the time so this lesson is going to spend a lot of time covering them.
The most simple SELECT
example would be this query, which will return all the columns and rows from the characters table:
SELECT * FROM "characters"
The asterisk (*) means that we want to grab all of the columns, without excluding anything. Since SQL databases usually consist of more then one table, the FROM
keyword is required to specify which table we want to look in.
Sometimes we don’t want all of the columns in a table. SQL allows us to choose and get only the ones we need: instead of putting the asterisk (*), we write the names of the desired columns.
SELECT name, weapon FROM "characters"
Also, in many cases we want the results be sorted in a certain way. In SQL we do this with ORDER BY.
It can take an optional modifier – ASC (default) or DESC for sorting direction:
SELECT name, weapon FROM "characters" ORDER BY name DESC
Bonus: Write a query that will SELECT
the name, race and hobby columns.
4. Where
You learned how to select only specific columns, but what if only certain rows need to be acquired. To the rescue here comes the WHERE
clause, allowing us to filter data depending on a condition.
In this query we select only those entries from the characters table, who use a pistol to fight baddies.
Bonus: Create a SELECT
query that fetches the name, race and hobby for those characters who are “Wookiees”.
5. AND / OR
WHERE
conditions can be made as specific as you like, with the help of the logical operators (AND,OR
) and math-like comparisons (=,<,>,<=,>=,<>).
Here we have a table containing the top 4 most sold albums of all time. Let’s select those of them that are classified as rock and have sold under 50 million copies. This can easily be done by placing the AND
operator between the two statements.
Bonus: Try and write an SQL query that returns the albums released after 1975 with sales less than 60 million.
6. In/Between/Like
WHERE statements also support a few special commands, allowing a quick way to check commonly used queries. They are:
- IN – compares the column to multiple possible values, resolves true if it matches at least one
- BETWEEN – checks if a value is within a range
- LIKE – searches for a specific pattern
For example if we want to do a query selecting the pop and soul albums from our table, we can use IN("value1","value2")
.
SELECT * FROM albums WHERE genre IN ('pop','soul');
If we want to get all the albums released between 1975 and 1985 we would write:
SELECT * FROM albums WHERE released BETWEEN 1975 AND 1985;
Bonus: All of the above operations can be reversed by placing NOT
in front of them. Try using NOT BETWEEN
to get the albums released before 1975 and after 1985.
7. Functions
SQL is packed with functions that do all sorts of helpful stuff. Here are some of the most regularly used ones:
COUNT()
– returns the number of rows
SUM()
– returns the total sum of a numeric column
AVG()
– returns the average of a set of values
MIN()
/ MAX()
– gets the minimum/maximum value from a column
To get the most recent year in our table we can run:
Bonus: Try combining SUM
with a WHERE
clause and fetch the combined sales of all rock albums.
8. Nested Select
In the previous point we learned how to do simple calculations with data. If we want to actually use the result from these calculations, often times a nested query (also known as sub select) is necessary. Let’s say we want to get the artist, album and release year for the oldest album in the table.
We know how to get these specific columns:
SELECT artist, album, released FROM albums;
We also know how to get the earliest year:
SELECT MIN(released) FROM album;
All that is needed now is to combine the two with the help of WHERE:
Bonus: Modify the above statement to return the album, genre and year for the newest album.
9. Joining Tables
In more complex databases, most of the time there are several tables connected to each other in some way. For example, below in the editor are two tables about video games and video game developers.
In the video_games table there is a developer column, but it holds an integer instead of the name of the developer. This number represents the id of the respective developer from the game_developers table, linking logically the two sheets, allowing us to use the information stored in both of them at the same time.
If we want to create a query that returns everything we need to know about the games, we can use INNER JOIN
to acquire the columns from both tables.
This is the simplest and most common type of JOIN
. There are a couple of other options, but they are applicable to less frequent scenarios. Chart of SQL Joins
10. Aliases
If you look at the previous example you’ll notice that there are two columns called name. That’s confusing, so let’s change it by setting an alias to one of the repeating columns: name from game_developers will appear as developer.
We can also shorten the query drastically by setting aliases to the table names: video_games becomes games and game_developers becomes devs.
11. Update
Often times we have to change the data in some of the rows. In SQL this is done via the UPDATE
statement.
The usage of UPDATE
consists of
- Choosing the table where the record we want to change is located.
- Setting new value(s) for the wanted column(s).
- Selecting with
WHERE
which of the rows we want to update. If this is omitted all rows in the table will change.
Here is a table of some of the highest rated TV series of all time. There is one tiny problem about it though, the show Game of Thrones is described as comedy, which it clearly isn’t. Let’s fix that!
Bonus: Let’s say that Breaking Bad is renewed for a new season. Write an SQL statement changing the still_running column to yes.
12. Delete Rows
Deleting a table row through SQL is a really simple process. All that is needed is to select the right table and row we want to remove.
Important: Always be cautions when writing a DELETE
statement and make sure there is a WHERE
clause attached. Without it all table rows will be deleted!
13. Deleting Tables
If we want to delete all the rows, but leave the table itself, the proper command is TRUNCATE:
TRUNCATE TABLE table_name;
In the case when we actually want to remove every trace of the table whatsoever, the DROP command comes into play:
DROP TABLE table_name;
Be very careful with these commands. There is no undo!
Conclusion
This wraps up our tutorial on SQL! There is a lot more to cover, but the above should be enough to give you a few practical skills in your web dev career.
For more information on SQL check out these great resources:
- Codeacademy SQL course – here
- SQL Fiddle: online tool for testing and sharing SQL – here
If you write copious amounts of CSS, a pre-processor can greatly decrease your stress levels and save you a lot of precious time. Using tools such as Sass, Less, Stylus or PostCSS makes large and complicated stylesheets clearer to understand and easier to maintain. Thanks to features like variables, functions and mixins the code becomes more organized, allowing developers to work quicker and make less mistakes.
We’ve worked with pre-processors before as you may remember from our article about Less. This time we are going to explain Sass and show you some of it’s main features.
1. Getting Started
Sass files cannot be interpreted by the browser, so they need compiling to standard CSS before they are ready to hit the web. That’s why you need some sort of tool to help you translate .scss files into .css. Here you have a couple of options:
- The simplest solution is a browser tool for writing and compiling Sass right on the spot – SassMeister.
- Use a 3rd party desktop app. Both free and paid versions are available. You can go here to find out more.
- If you are a CLI person like we are, you can install Sass on your computer and compile files manually.
If you decide to go with the command line, you can install Sass in it’s original form (written in ruby) or you can try the Node.js port (our choice). There are many other wrappers as well, but since we love Node.js we are going to go with that.
Here is how you can compile .scss files using the node CLI:
node-sass input.scss output.css
Also, here is the time to mention that Sass offers two distinct syntaxes – Sass and SCSS. They both do the same things, just are written in different ways. SCSS is the newer one and is generally considered better, so we are going to go with that. If you want more information on the difference between the two, check out this great article.
2. Variables
Variables in Sass work in a similar fashion to the those in any programming language, including principals such as data types and scope. When defining a variable we store inside it a certain value, which usually is something that will often reoccur in the CSS like a palette color, a font stack or the whole specs for a cool box-shadow.
Below you can see a simple example. Switch between the tabs to see the SCSS code and it’s CSS translation.
$title-font: normal 24px/1.5 'Open Sans', sans-serif;
$cool-red: #F44336;
$box-shadow-bottom-only: 0 2px 1px 0 rgba(0, 0, 0, 0.2);
h1.title {
font: $title-font;
color: $cool-red;
}
div.container {
color: $cool-red;
background: #fff;
width: 100%;
box-shadow: $box-shadow-bottom-only;
}
h1.title {
font: normal 24px/1.5 "Open Sans", sans-serif;
color: #F44336;
}
div.container {
color: #F44336;
background: #fff;
width: 100%;
box-shadow: 0 2px 1px 0 rgba(0, 0, 0, 0.2);
}
The idea behind all this is that we can later on reuse the same values more quickly, or if a change is needed, we can provide the new value in just one place (the definition of the variable), instead of applying it manually everywhere we’re using that property.
3. Mixins
You can think of mixins as a simplified version of constructor classes in programming languages – you can grab a whole group of CSS declarations and re-use it wherever you want to give and element a specific set of styles.
Mixins can even accept arguments with the option to set default values. In the below example we define a square mixin, and then use it to create squares of varying sizes and colors.
@mixin square($size, $color) {
width: $size;
height: $size;
background-color: $color;
}
.small-blue-square {
@include square(20px, rgb(0,0,255));
}
.big-red-square {
@include square(300px, rgb(255,0,0));
}
.small-blue-square {
width: 20px;
height: 20px;
background-color: blue;
}
.big-red-square {
width: 300px;
height: 300px;
background-color: red;
}
Another efficient way to use mixins is when a property requires prefixes to work in all browsers.
@mixin transform-tilt() {
$tilt: rotate(15deg);
-webkit-transform: $tilt; /* Ch <36, Saf 5.1+, iOS, An =<4.4.4 */
-ms-transform: $tilt; /* IE 9 */
transform: $tilt; /* IE 10, Fx 16+, Op 12.1+ */
}
.frame:hover {
@include transform-tilt;
}
.frame:hover {
-webkit-transform: rotate(15deg); /* Ch <36, Saf 5.1+, iOS, An =<4.4.4 */
-ms-transform: rotate(15deg); /* IE 9 */
transform: rotate(15deg); /* IE 10, Fx 16+, Op 12.1+ */
}
4. Extend
The next feature we will look at is @extend
, which allows you to inherit the CSS properties of one selector to another. This works similarly to the mixins system, but is preferred when we want to create a logical connection between the elements on a page.
Extending should be used when we need similarly styled elements, which still differ in some detail. For example, let’s make two dialog buttons – one for agreeing and one for canceling the dialog.
.dialog-button {
box-sizing: border-box;
color: #ffffff;
box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.12);
padding: 12px 40px;
cursor: pointer;
}
.confirm {
@extend .dialog-button;
background-color: #87bae1;
float: left;
}
.cancel {
@extend .dialog-button;
background-color: #e4749e;
float: right;
}
.dialog-button, .confirm, .cancel {
box-sizing: border-box;
color: #ffffff;
box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.12);
padding: 12px 40px;
cursor: pointer;
}
.confirm {
background-color: #87bae1;
float: left;
}
.cancel {
background-color: #e4749e;
float: right;
}
If you check out the CSS version of the code, you will see that Sass combined the selectors instead of repeating the same declarations over and over, saving us precious memory.
5. Nesting
HTML follows a strict nesting structure whereas in CSS it’s usually total chaos. With Sass nesting you can organize your stylesheet in a way that resembles the HTML more closely, thus reducing the chance of CSS conflicts.
For a quick example, lets style a list containing a number of links:
ul {
list-style: none;
li {
padding: 15px;
display: inline-block;
a {
text-decoration: none;
font-size: 16px;
color: #444;
}
}
}
ul {
list-style: none;
}
ul li {
padding: 15px;
display: inline-block;
}
ul li a {
text-decoration: none;
font-size: 16px;
color: #444;
}
Very neat and conflict proof.
6.Operations
With Sass you can do basic mathematical operation right in the stylesheet and it is as simple as applying the appropriate arithmetic symbol.
$width: 800px;
.container {
width: $width;
}
.column-half {
width: $width / 2;
}
.column-fifth {
width: $width / 5;
}
.container {
width: 800px;
}
.column-half {
width: 400px;
}
.column-fifth {
width: 160px;
}
Although vanilla CSS now also offers this feature in the form of calc(), the Sass alternative is quicker to write, has the modulo %
operation, and can be applied to a wider range of data-types (e.g. colors and strings).
7. Functions
Sass offers a long list of built-in functions. They serve all kinds of purposes including string manipulation, color related operations, and some handy math methods such as random() and round().
To exhibit one of the more simple Sass functions, we will create a quick snippet that utilizes darken($color, $amount) to make an on-hover effect.
$awesome-blue: #2196F3;
a {
padding: 10 15px;
background-color: $awesome-blue;
}
a:hover {
background-color: darken($awesome-blue,10%);
}
a {
padding: 10 15px;
background-color: #2196F3;
}
a:hover {
background-color: #0c7cd5;
}
Except the huge list of available functions, there is also the options to define your own. Sass supports flow control as well, so if you want to, you can create quite complex behaviors.
Conclusion
Some of the above features are coming to standard CSS in the future, but they are not quite here yet. In the meantime, pre-processors are a great way improve the CSS writing experience and Sass is a solid option when choosing one.
We only covered the surface here, but there is a lot more to Sass than this. If you want to get more familiar with everything it has to offer, follow these links:
Now is a fantastic time to be a web developer. The community creates lots of new and exciting JavaScript and CSS libraries, so there is always something new to learn and see. Here are some of our favorites, which we think that you should check out in January 2016.
Datedropper is a jQuery plugin which helps you create an interesting way for presenting date fields. It supports 16 languages and all date formats. It has a lot of useful options and eye-catching animation. It is very easy to use – just embed the JavaScript file in your page and initialize the date field with the dateDropper()
method.
Drop.js is a useful JavaScript and CSS library for creating dropdowns and floating displays. It’s animated smoothly with CSS and you can embed whatever HTML code you wish in the dropdown.
Vorlon.js is a cross platform tool, developed by Microsoft, that helps you remotely debug and test your JavaScript. It gives you the ability to remotely connect up to 50 devices and easily test your code on all of them simultaneously. There is also a desktop application, built using Electron, which helps you run your tests from an easy to use graphical app.
Hammer is an open-source library that recognizes gestures made by touch, mouse and pointer events. It supports complex multi-touch gestures like rotate, pinch and swipe, which makes it possible to develop web apps that can rival the experience that native applications provide.
Vivus is a JavaScript class that helps you bring your SVGs to life, giving them the appearance of being drawn. It is standalone and has no dependencies. It supports a lot of animation types and timing options, as well as option to script your own animations with JavaScript.
Popmotion is JavaScript motion engine, with physics and input tracking. It gives you a great deal of control over every aspect of your animations. You can define custom easing transitions, pause, reverse and seek animations and more. It supports CSS and SVG animations which work smoothly on any browser.
Animateplus is a CSS and SVG animation library. It works very well on mobile devices, and is perfect for smooth landing pages. You can configure the duration, easing and delay before the animation starts.
Dinamics.js is JavaScript library that helps you create physics-based animations. It has a lot of useful options like friction, bounciness and elasticity. You can animate all your menus, load elements and buttons. Their website has lots of pretty examples which you can start with.
Gradient animator is an online tool that helps you generate animated CSS gradients. After you choose options like colors speed and angles, just copy the code that the website gives you and paste it into your stylesheet.
Notie Is clean and simple notification library for JavaScript. It supports many types of notifications including alternatives for the confirm and prompt browser dialogs. The library gives you an easy way to override the way noties look and feel, so you can customize everything to match your design.
OhSnap! Is a simple notification library for jQuery/Zepto. It is designed to work well in both desktop and mobile browsers. It is very easy to integrate into an existing website. To customize it you only need to edit a single .css file.
Purify is a utility which cleans up your CSS. It has the ability to detect the dynamically-loaded CSS selectors in your JavaScript. It works with single-page as well as multi-page apps.
Wheelnav is JavaScript library, built on SVG, for tab navigation and wheel menus. It has the option to create collapsible pie menus with optional sub menus. Despite that the default appearance is a wheel you can modify your menu easily.
SpaceBase is a Sass-based framework that combines the best responsive practices into ready-to-use boilerplate project. It contains must-haves like a mobile-friendly grid, common ui components like buttons and lists, help classes and mixins and more.
Egg.js is a simple library that helps you add a web easter egg by watching the user’s key strokes. You can add a hook that will run after any egg code is triggered. You can use this to send out a tweet that someone found your easter egg.
Here we have for you a collection of 12 lovely free templates for displaying various item lists! We’ve created them without relying on any frameworks or libraries, only vanilla HTML and CSS have been used. Because of this, they are very easy to implement and can pair well with all kinds of websites, apps and blogs.
The Templates
The templates are separated in 4 different groups. Here’s what we have:
- 3 Product lists, perfect for online shops and catalogs.
- 4 Article lists for presenting blog posts with thumbnails, titles and descriptions.
- 2 Image lists for displaying galleries and photo albums.
- 3 User profile lists showing quick information about a person and their avatar.
You can download the entire pack from the Download button near the top of the page.
Using the Templates
After you’ve downloaded them, placing any of the templates in you projects is pretty straightforward. Just follow these easy steps:
- Choose the template you like best.
- Open it’s example, copy the HTML inside the
<body>
tag and paste it wherever you want the list in your page.
- Get the corresponding CSS file for this particular template and link it to your project (the stylesheets are located in /assets/css). Our CSS is self contained and won’t interfere with the rest of your styles.
- Replace our placeholder content with your text and images.
- Done!
User Profiles Small
Free for Commercial Use
All 12 templates are completely free of charge and don’t require any form of attribution. You have all rights to customize them and use them however you want, in both personal and commercial projects (our license page). Enjoy!
Web applications become more and more powerful every year, but there is still room for desktop apps with full access to the hardware of your computer. Today you can create desktop apps using the already familiar HTML, JS and Node.js, then package it into an executable file and distribute it accordingly across Windows, OS X and Linux.
There are two popular open source projects which make this possible. These are NW.js, which we covered a few months ago, and the newer Electron, which we are going to use today (see the differences between them here). We are going to rewrite the older NW.js version to use Electron, so you can easily compare them.
Getting Started With Electron
Apps built with Electron are just web sites which are opened in an embedded Chromium web browser. In addition to the regular HTML5 APIs, these websites can use the full suite of Node.js modules and special Electron modules which give access to the operating system.
For the sake of this tutorial, we will be building a simple app that fetches the most recent Tutorialzine articles via our RSS feed and displays them in a cool looking carousel. All the files needed for the app to work are available in an archive which you can get from the Download button near the top of the page.
Extract its contents in a directory of your choice. Judging by the file structure, you would never guess this is a desktop application and not just a simple website.
Directory Structure
We will take a closer look at the more interesting files and how it all works in a minute, but first, let’s take the app for a spin.
Running the App
Since an Electron app is just a fancy Node.js app, you will need to have npm installed. You can learn how to do it here, it’s pretty straightforward.
Once you’ve got that covered, open a new cmd or terminal in the directory with the extracted files and run this command:
npm install
This will create a node_modules folder containing all the Node.js dependencies required for the app to work. Everything should be good to go now, in the same terminal as before enter the following:
npm start
The app should open up in it’s own window. Notice it has a top menu bar and everything!
Electron App In Action
You’ve probably noticed that starting the app isn’t too user friendly. However, this is just the developer’s way of running an Electron app. When packaged for the public, the it will be installed like a normal program and opened like one, just by double clicking on its icon.
How it’s made
Here, we will talk about the most essential files in any electron app. Let’s start with package.json, which holds various information about the project, such as the version, npm dependencies and other important settings.
package.json
{
"name": "electron-app",
"version": "1.0.0",
"description": "",
"main": "main.js",
"dependencies": {
"pretty-bytes": "^2.0.1"
},
"devDependencies": {
"electron-prebuilt": "^0.35.2"
},
"scripts": {
"start": "electron main.js"
},
"author": "",
"license": "ISC"
}
If you’ve worked with node.js before, you already know how this works. The most significant thing to note here is the scripts property, where we’ve defined the npm start
command, allowing us to run the app like we did earlier. When we call it, we ask electron to run the main.js file. This JS file contains a short script that opens the app window, and defines some options and event handlers.
main.js
var app = require('app'); // Module to control application life.
var BrowserWindow = require('browser-window'); // Module to create native browser window.
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var mainWindow = null;
// Quit when all windows are closed.
app.on('window-all-closed', function() {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform != 'darwin') {
app.quit();
}
});
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
// Create the browser window.
mainWindow = new BrowserWindow({width: 900, height: 600});
// and load the index.html of the app.
mainWindow.loadURL('file://' + __dirname + '/index.html');
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
});
Take a look at what we do in the ‘ready’ method. First we define a browser window and set it’s initial size. Then, we load the index.html file in it, which works similarly to opening a HTML file in your browser.
As you will see, the HTML file itself is nothing special – a container for the carousel and a paragraph were CPU and RAM stats are displayed.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Tutorialzine Electron Experiment</title>
<link rel="stylesheet" href="./css/jquery.flipster.min.css">
<link rel="stylesheet" href="./css/styles.css">
</head>
<body>
<div class="flipster">
<ul>
</ul>
</div>
<p class="stats"></p>
<!-->In Electron, this is the correct way to include jQuery<-->
<script>window.$ = window.jQuery = require('./js/jquery.min.js');</script>
<script src="./js/jquery.flipster.min.js"></script>
<script src="./js/script.js"></script>
</body>
</html>
The HTML also links to the needed stylesheets, JS libraries and scripts. Notice that jQuery is included in a weird way. See this issue for more information about that.
Finally, here is the actual JavaScript for the app. In it we access Tutorialzine’s RSS feed, fetch recent articles and display them. If we try to do this in a browser environment, it won’t work, because the RSS feed is located on a different domain and fetching from it is forbidden. In Electron, however, this limitation doesn’t apply and we can simply get the needed information with an AJAX request.
$(function(){
// Display some statistics about this computer, using node's os module.
var os = require('os');
var prettyBytes = require('pretty-bytes');
$('.stats').append('Number of cpu cores: <span>' + os.cpus().length + '</span>');
$('.stats').append('Free memory: <span>' + prettyBytes(os.freemem())+ '</span>');
// Electron's UI library. We will need it for later.
var shell = require('shell');
// Fetch the recent posts on Tutorialzine.
var ul = $('.flipster ul');
// The same-origin security policy doesn't apply to electron, so we can
// send ajax request to other sites. Let's fetch Tutorialzine's rss feed:
$.get('http://feeds.feedburner.com/Tutorialzine', function(response){
var rss = $(response);
// Find all articles in the RSS feed:
rss.find('item').each(function(){
var item = $(this);
var content = item.find('encoded').html().split('</a></div>')[0]+'</a></div>';
var urlRegex = /(http|ftp|https)://[w-_]+(.[w-_]+)+([w-.,@?^=%&:/~+#]*[w-@?^=%&/~+#])?/g;
// Fetch the first image of the article.
var imageSource = content.match(urlRegex)[1];
// Create a li item for every article, and append it to the unordered list.
var li = $('<li><img /><a target="_blank"></a></li>');
li.find('a')
.attr('href', item.find('link').text())
.text(item.find("title").text());
li.find('img').attr('src', imageSource);
li.appendTo(ul);
});
// Initialize the flipster plugin.
$('.flipster').flipster({
style: 'carousel'
});
// When an article is clicked, open the page in the system default browser.
// Otherwise it would open it in the electron window which is not what we want.
$('.flipster').on('click', 'a', function (e) {
e.preventDefault();
// Open URL with default browser.
shell.openExternal(e.target.href);
});
});
});
A cool thing about the above code, is that in one file we simultaneously use:
- JavaScript libraries – jQuery and jQuery Flipster to make the carousel.
- Electron native modules – Shell which provides APIs for desktop related tasks, in our case opening a URL in the default web browser.
- Node.js modules – OS for accessing system memory information, Pretty Bytes for formatting.
And with this our app is ready!
Packaging and Distribution
There is one other important thing to do to make your app ready for end users. You need to package it into an executable that can be started with a double click on users’ machines. Since Electron apps can work on multiple operating systems and every OS is different, there need to be separate distributions for Windows, for OS X and for Linux. Tools such as this npm module are a good place to start – Electron Packager.
Take into consideration that the packaging takes all your assets, all the required node.js modules, plus a minified WebKit browser and places them together in a single executable file. All these things sum up and the final result is an app that is roughly 50mb in size. This is quite a lot and isn’t practical for a simple app like our example here, but this becomes irrelevant when we work with big, complex applications.
Conclusion
The only major difference with NW.js that you will see in our example is that NW.js opens an HTML page directly, whereas Electron starts up by executing a JavaScript file and you create an application window through code. Electron’s way gives you more control, as you can easily build multi-window applications and organize the communication between them.
Overall Electron is an exciting way to build desktop web applications using web technologies. Here is what you should read next:
A lot happened in the software development world in 2015. There were new releases of popular programming languages, new versions of important frameworks and new tools. You will find a short list of the new releases that we think are the most important below, together with suggestions for the things we believe would be a great investment of your time to learn in 2016.
The Trends
Shift from the backend to the frontend
In the last few years, there has been a trend towards shifting the business logic of web apps from the backend to the frontend, with the backend being delegated to a simple API. This makes the choice of a frontend framework that much more important.
Quick browsers releases
Another significant advancement for the web as a platform in 2015 was the release of the Edge web browser. This is the successor of Internet Explorer which has an updated interface and faster performance. What sets it apart from IE is that it adopts the same quick release schedule that Firefox and Chrome follow. This is going to move the JavaScript community forward as updates to JavaScript and web standards will be available in weeks rather than years everywhere.
The death of Flash
It has finally happened! YouTube switched to HTML5 this year, ditching their legacy Flash player. Firefox started blocking the Flash plugin by default. Even the powerful Adobe Flash creation suite was renamed to Adobe Animate and defaults to HTML5 exports. This leaves the doors wide open for the web platform to shine.
Languages and Platforms
Python 3.5 was released this year with a lot of new features like Asyncio, which gives you a node.js-like event loop, and type hints. As a whole Python 3 is finally gaining popularity and we heavily recommend it over the older Python 2. Nearly all libraries are available for Python 3 and now is a good time to upgrade your legacy code base.
PHP 7 is a major new version that fixes a number of issues and brings new features and speed (see an overview here). PHP 7 is around twice as fast as PHP 5.6, which will have a big impact on large codebases and CMS systems like WordPress and Drupal. We recommend PHP The Right Way, which was updated for version 7. And if you need even more speed and don’t mind switching to an alternative runtime, check out HHVM, which Facebook uses and develops to run their website.
JavaScript also saw updates in the form of the ES2015 standard (used to be known as ES6). It brings us exciting new features and additions to the language. Thanks to most browsers adopting quick release schedules, support for ES2015 is great, and there is Babel.js which will help you bring your code to older browsers.
Node.js saw a lot of changes this year, with the community splitting between Node.js and io.js, and then joining forces again. As a result we now have an actively maintained project with lots of contributors and two versions of Node – a solid LTS (long term support) release, which gives stability for long lived projects and large companies, and a non-lts version which is quick to add new JavaScript features.
Swift 2 was released earlier this year. This is Apple’s vision for a modern programming language that eases the development of apps on iOS and OS X. As of a few weeks ago, Swift is open source and has already been ported on Linux. This means that it is now possible to build backends and server side software with it.
Go 1.5 was released a few months ago, and brough major architectural changes. In 2015 it has grown in popularity and has been adopted in leading startups and open source projects. The language itself is relatively simple, so learning it will be a weekend well spent.
TypeScript is a staticly typed language which compiles to JavaScript. It is developed by Microsoft and has perfect integration with Visual Studio and the open source Visual Studio Code editors. It will soon be quite popular, as the upcoming Angular 2 is written in it. Static typing benefits large teams and large code bases the most, so if one of these applies to you, or you are just curious, you should give TypeScript a try.
For the adventurous, you can try out one the functional languages like Haskell or Clojure. There are also interesting high performance languages like Rust and Elixir. If you are looking for a programming job, career languages like Java (which has some nice features in its 8th version) and C# (which thanks to Visual Studio Code and .net core can be run and developed cross platform) would be a good investment of your time in 2016.
Learn one or more of these: Python 3, Go, PHP 7, ES2015, Node.js, Swift, TypeScript
JavaScript Frameworks
JavaScript is a very important piece of the web development stack, so we are giving it dedicated section in our overview. There were two new standards this year – Service Workers and Web Assembly, which shape how web apps are developed from now on. There were also a number of new framework releases which we think you should keep a close eye on in 2016:
Angular.js has become the go-to JavaScript framework for enterprises and large companies. It has been known for some time that the next major version of the framework was coming, and earlier this year Angular 2 was released as a development preview. It is a total rewrite of Angular 1 and according to us is a great improvement over it. It is almost guaranteed to become the enterprise framework of choice once it is released, and Angular 2 experience will be a great addition to your CV. Our advice is to wait a few months for the final version to ship before picking it up, but you can read through their quick start guide right now.
React continued its ascend throughout 2015 and has seen new releases throughout the year and new projects adopting it as their library of choice. It shipped new development tools a few months ago. Facebook also released React Native which is a framework for building mobile apps for Android and iOS, which combines a native frontend with React running in a background JavaScript thread. See a quick tutorial about React that we published this year.
Polymer 1.0 was released in May. This marks the first stable and production ready version. Polymer is based around Web Components, which is a standard for packaging HTML, JS and CSS into isolated widgets that can be imported into your web apps. Web Components are only supported in Chrome and Opera at the moment, but Polymer makes them available everywhere.
Ember.js also saw a new release. Ember 2 brings modularity and removes deprecated features and optimizes the codebase. Ember follows semantic versioning and maintainers of the framework are careful to make updating as easy as possible. If you need a framework with stability and easy migration to new versions, you can give Ember a try.
Vue.js is a new library that offers reactive components for building user interfaces. It supports data binding, modular components and composition. It is similar to React, but doesn’t use a virtual DOM and works only in the browser. In the short time that it has existed, Vue has gathered a very active community around it and is establishing itself as a pragmatic tool for building web interfaces.
Learn one of these: Angular 2, React, Ember.js, Vue.js, Polymer, Web Components, Service Workers
Frontend
Bootstrap has become even more popular in the last year and is turning into a web development standard. Version 4 will come out in the next few months, which brings flexbox support and integrates SASS. It promises a smooth transition from V3 (unlike what we saw with v2 to v3 a couple of years ago), so you can feel confident that what you learn about Bootstrap 3 will be applicable to version 4.
Foundation is another frontend framework that is an alternative to Bootstrap. Version 6 was released earlier this year, which focuses on modularity so that you can include only the pieces that you need for a faster load time.
MDL is an official framework by Google for building material design web apps. It was released earlier this year and has a similar goal to Google’s other framework – Polymer, but is much easier to get started with. We have a wonderful overview which compares MDL with Bootstrap.
CSS preprocessors continue improving. Less and SASS are the two most popular at the moment, with mostly comparable feature sets. However, the news that Bootstrap 4 is migrating over to SASS gives it a slight edge over Less as the preprocessor to learn in 2016. Also, there is the newer PostCSS tool that is gaining mind share, but we recommend it only for devs which already have experience with preprocessors.
Learn one or more of these: Bootstrap, MDL, Foundation, SASS, LESS, PostCSS
Backend
There has been a clear trend in web development over the last few years. More and more of our apps’ logic is shifted to the frontend, and the backend is only treated as an API. However there is still room for classic HTML-generating web apps, which is why we think that learning a classic full stack framework is still important.
Depending on which language you prefer, you have plenty of choice. For PHP you have Symfony, Zend, Laravel (and Lumen, its new lightweight alternative for APIs), Slim and more. For Python – Django and Flask. For Ruby – Rails and Sinatra. For Java – Play and Spark. For Node.js you have Express, Hapi and Sails.js, and for Go you have Revel.
AWS Lambda was released last year, but the concept is now established and ready for production. This is a service which eliminates backend servers entirely and is infinitely scaleable. You can define functions which are called on specific conditions or when routes of your API are visited. This means that you can have an entirely serverless backend which you don’t have to think about.
Another trend are static site generators like Jekyll and Octopress (see a complete list here). These tools take a number of source files like text and images, and create an entire website with prerendered HTML pages. Developers, who would normally set up a WordPress blog with a database and an admin area, now prefer to generate their HTML pages ahead of time and only upload a static version of their site. This has the benefits of increased security (no backend to hack and database to manage) and fantastic performance. Combined with CDNs like MaxCDN and CloudFlare clients can request a page of the website and receive it from a server nearby, greatly reducing latency.
Learn one of these: A full stack backend framework, AWS Lambda, A static site generator
CMS
We’ve included two of the most popular CMS systems here. Both are written in PHP and are easy to deploy and get started with. They enjoy big speedups from the new PHP 7 release.
In recent years WordPress has become much more than a simple blogging platform. It is a fully fledged CMS/Framework with plugins that make it possible to run any kind of website. High quality WordPress themes are a big market, and lots of freelancers make their living by developing for WordPress. With projects like WP-API you can use WordPress as a REST API backend.
Drupal 8 was released this year. It is a full rewrite that focuses on modern development practices. It makes use of Symfony 2 components and Composer packages and the Twig templating engine. Millions of websites run Drupal, and it is a good choice for content heavy portals.
Databases
This year the web development community lost some of its enthusiasm for NoSQL databases, and instead returned to relational databases like Postgres and MySQL. Notable exceptions to this trend are RethinkDB and Redis which gained mind share, and we recommend that you try them out in 2016.
Postgres is a popular relational database engine which sees a lot of development activity and is constantly improved with new features. Version 9.5 is expected soon. It will bring better support for JSONB columns for holding schema-less data (replacing any need for a separate NoSQL database) and the long awaited upsert operation, which simplifies INSERT-or-UPDATE queries. You might want to look into it, once it is released in 2016.
MySQL is the the most popular open source database system and is installed on most hosting providers out there. With version 5.7, MySQL also offers JSON columns for storing schema-less data. If you are just starting out with backend development, you will most likely be looking at connecting to a MySQL database that your hosting provider has set up for you. It is probably going to be an older version, so you might not be able to try out the JSON type. MySQL is included in popular packages like XAMPP and MAMP so it is easy to get started with.
Learn one of these: Redis, RethinkDB, MySQL/MariaDB, PostgreSQL
Mobile Apps
Mobile platforms are always evolving and smartphone hardware now rivals low end laptops in performance. This is great news for hybrid mobile frameworks, as mobile apps built using web technologies can now offer a smooth, native-like experience.
We have a nice overview of hybrid mobile frameworks that you might want to check out. You have the popular Ionic framework and Meteor which recently had its 1.0 version and is also suitable for mobile app development. Facebook launched React Native, which runs React components in a background JavaScript thread and updates a native UI, allowing you to have mostly identical code for both iOS and Android.
Learn one of these: Ionic, React Native, Meteor
Editors and Tools
The Atom editor reached version 1.0 this year. It is a free and powerful code editor that is built using web technologies. It has lots of packages available for it and a large community. It offers smart autocompletion and integrates with plugins for code refactoring and linting. Not to mention that it has lots of beautiful themes to chose from, and you can customize it by writing CoffeeScript and CSS. Facebook has used this extensibility and launched the Nuclide editor.
Microsoft surprised everybody when they released their Visual Studio Code editor earlier this year. It is a lightweight IDE that supports a number of languages and runs on Windows, Linux and OS X. It offers the powerful IntelliSense code inspection feature and integrates a debugger for ASP.Net and Node.js.
NPM, the package manager of Node.js, has exploded in popularity and has become the packaging standard for frontend and node developers. This is the easiest way to manage the JavaScript dependencies for your project and getting started with it is easy.
Even for a solo developer Git is a necessity these days. Its serverless model allows you to turn any folder into a version controlled repository, which you can then push to Bitbucket or Github, and sync across computers. If you haven’t used Git yet, we recommend that you add it to your list of things to learn in 2016.
Learn one of these: Atom, Visual Studio Code, NPM, Git
Making Things
The Raspberry PI foundation delivered an early Christmas present this year, with the release of the Raspberry PI Zero – a $5 computer that is fast and power efficient. It runs Linux, so you can turn it into a server, a home automation device, a smart mirror, or to embed it into a dumb appliance and create that internet enabled coffee brewer you’ve been dreaming of. 2016 is the year to get a Raspberry.
Onto An Awesome 2016!
We’ve had a great 2015 and by the looks of it 2016 is going to be even more awesome. What’s on your list of things to learn in 2016?
Oh StackOverflow, what would we do without you! You save us countless hours of bug fixing with a single spot on answer. But there was a time when Stack Overflow wasn’t only for technical answers, and a few entertaining gems could slip through. We’ve collected a few of our most favorite ones for your enjoyment.
Our Top 10
Here are our favorite entertaining Stack Overflow questions. They aren’t sorted by up votes or anything, we are going to let you decide which ones you like best. If we’ve missed your favorite, add it to our comment section!
Although this question is from 2011 and no one uses the HTML bgcolor
attribute anymore, it’s still funny that someone tried to color their div chucknorris. Also, in case you were wondering, here is a chart showing which color represents the names of popular celebrities.
A huge compilation of funny images and comics. Be careful, you might waste an entire work day with this one. Credit goes to xkcd for providing us with nerdy entertainment.
Some people don’t comment their code at all causing confusion and bewilderment, others add meaningful and on point hints to aid their colleagues and their future selves. And then there are the people in this thread.
Some of these are bad, some of these are good, some of these are so bad they are good. You know a good joke that is not in the list? Post it to our comment section!
Ever feel like your amazing programming skills are useless outside of the computer world? This questions proves they aren’t! Apply your knowledge and fix a very real everyday laundry problem.
This question is another evidence that Stack Overflow has a sense of humor. Choose your favorite answer and the next time someone asks you this question seize the opportunity!
Have you ever needed to style only half of a character? Neither have we, but surprisingly it is possible! In an incredibly detailed answer, the stack overflow user Arbel shows different techniques for doing it. The code has been released as a jQuery plugin.
How many checkboxes could a checkbox check if a checkbox could check checkboxes? But no, seriously, this is a helpful question solving a very common problem.
JavaScript is a weird language that often times works in mysterious and unpredictable ways. The snipped in question is not Brainfuck but valid JavaScript. Thankfully Stack Overflow is full with people who now their JS, and they took the time to explain how this mind bending code works.
Have you ever thought about how much you hate your workplace? Well, at lest it doesn’t impose nonsensical coding standard rules like the ones in this thread.
Bonus
This question was asked in the java section, but the topic applies to all programming languages – random isn’t really random, it’s pseudorandom. Feel free to use this information to confuse other coders.
Your favorite web scripting language just got even better! The 2015 edition of ECMAScript comes with a ton of cool new techniques and programming concepts, much anticipated by the JavaScript community. Most of the new features are already available out of the box with modern browsers and Node.js, and are expected to receive wide support soon.
We’ve prepared a fun quiz which you can take to see how much you know about ES6 (aka ES2015), and maybe learn a few new things as well!
(See this quiz on Tutorialzine.com)
Flexbox is a powerful new way for building layouts that makes some of the most challenging aspects of web development trivial. Nearly all browsers that are used today support it, so it is a good time to see how it can fit in your typical day-to-day frontend work.
This is why in this quick tutorial we’re going to build a comment section using flexbox. We’ll take a look at some of the more interesting properties that the flexbox layout mode has to offer and show you how to take full advantage of it.
What We’re Going to Use
Flexbox consists of a number of CSS properties, some of which we are going to use today:
display: flex
– This activates the flex layout mode and makes the element’s children follow flexbox rules.
justify-content
– This property defines where the children of a flexbox element will align to (this is similar to text-align, read more here).
order
– Flexbox gives us control on the exact position elements are displayed at. We use this powerful tool in our comment section to switch the text and photo around (find out more here).
flex-wrap
– Controls the wrapping of the elements within the flex element. We use this to force the avatars to show beneath the comment text on small screens (flex-wrap on MDN).
The Layout
We want our comment section to meet the following requirements:
- Each comment should have an avatar, name, time and comment body.
- There should be two comment types – those written by the author (colored in blue and having the avatar on the right) and those written by everyone else.
- The HTML markup for both types of comments has to be as similar as possible, so it is easy to generate comments through code.
- The whole thing has to be fully responsive.
Comment Section Layout
All of this can be made with a few lines of CSS with flexbox. Let’s move on the the code!
The HTML
Our HTML is pretty straightforward. We’ll have a list of comments with a basic form for writing new comments at the end.
<ul class="comment-section">
<li class="comment user-comment">
<div class="info">
<a href="#">Anie Silverston</a>
<span>4 hours ago</span>
</div>
<a class="avatar" href="#">
<img src="images/avatar_user_1.jpg" width="35" alt="Profile Avatar" title="Anie Silverston" />
</a>
<p>Suspendisse gravida sem?</p>
</li>
<li class="comment author-comment">
<div class="info">
<a href="#">Jack Smith</a>
<span>3 hours ago</span>
</div>
<a class="avatar" href="#">
<img src="images/avatar_author.jpg" width="35" alt="Profile Avatar" title="Jack Smith" />
</a>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse gravida sem sit amet molestie portitor.</p>
</li>
<!-- More comments -->
<li class="write-new">
<form action="#" method="post">
<textarea placeholder="Write your comment here" name="comment"></textarea>
<div>
<img src="images/avatar_user_2.jpg" width="35" alt="Profile of Bradley Jones" title="Bradley Jones" />
<button type="submit">Submit</button>
</div>
</form>
</li>
</ul>
If you look closely at the above code, you’ll notice that apart from having different classes, the HTML for the user comments and the author comments are practically the same. All of the stylistic and layout differences between the two, will be handled solely by CSS applied to the .user-comment
and .author-comment
classes.
The CSS
Here we’re going to look at flexbox-related techniques we’ve used when building the layout. If you want to examine the stylesheet in full detail, download the whole CSS file from the button near the top of the article.
First off, we are going to give all comments display: flex
, which will enable us to use the flexbox properties on the comments and their child elements.
.comment{
display: flex;
}
These flex containers span the full width of our comment section and hold the user info, avatar and message. Since we want the comments written by the author to be aligned to the right, we can use the following flex property and align everything towards the end of our container.
.comment.author-comment{
justify-content: flex-end;
}
This will leave the comments looking like this:
justify-content: flex-end
Now we have the author comment aligned on the right, but we also want to have the elements inside the container in reverse order, so that the message comes first, then the avatar and the info on the far right. To do this we will take advantage of the order
property.
.comment.author-comment .info{
order: 3;
}
.comment.author-comment .avatar{
order: 2;
}
.comment.author-comment p{
order: 1;
}
As you can see, with the help of flexbox, the whole thing couldn’t be any easier.
Reordering Elements
Our comment section looks just like we wanted it to. The only thing left to do is make sure that it looks good on smaller devices as well. Since there won’t be as much available space on a narrower screen, we’ll have to do some rearrangements to the layout and make our content more easily readable.
We set up a media query that makes the comment paragraphs expand, taking up the whole width of the container. This will lead to the avatar and user info moving to the next line, since the comments have their flex-wrap
property set to wrap
.
@media (max-width: 800px){
/* Reverse the order of elements in the user comments,
so that the avatar and info appear after the text. */
.comment.user-comment .info{
order: 3;
}
.comment.user-comment .avatar{
order: 2;
}
.comment.user-comment p{
order: 1;
}
/* Make the paragraph in the comments take up the whole width,
forcing the avatar and user info to wrap to the next line*/
.comment p{
width: 100%;
}
/* Align toward the beginning of the container (to the left)
all the elements inside the author comments. */
.comment.author-comment{
justify-content: flex-start;
}
}
The difference can be spotted right away by comparing this screen capture with the one above. You can also try opening the demo and resizing your browser to watch the comment section adapt accordingly to the size of the window.
Our comment section on smaller screens
Conclusion
This sums up our tutorial. We hope that this gave you a practical example on how to use flexbox when building real layouts. If you’re curious what else is possible, here are a few great resources that you’ll like:
- CSS-Tricks’ guide to flexbox – here.
- An in-depth MDN article – here.
- A website with easy flexbox solutions for classic CSS problems – here.