Golang – labeled break and continue

break and continue are keywords that control the loop in many programming languages. The scope of those keywords is at inner most. Here is the example code of C++.

for (int i = 0; i < 5; ++i) {
    for (int j = 0; j < 5; ++j) {
        if (i == 1 && j == 3) {
            break;
            // continue;
        }
    }
}

In the example code above, break and continue will only affect the inner most loop which deals with the variable j. However, in golang, you can control the scope of break and continue keyword by using labels.

Here is the example code.

package main

import (
	"fmt"
	"os"
	"strings"
)

func main() {
	library := `
	I am learning computer science and computer engineering
	`
	words := strings.Fields(library)
	query := os.Args[1:]

queries:
	for _, q := range query {
		for i, w := range words {
			if q == w {
				fmt.Printf("index %d: %q\n", i, w)
				break queries
			}
		}
	}
}

Let’s say there is a library of words and you are querying unique words. For example, when you query the word computer, it should return the first index of the word and the word itself. As you are running the loop, there are multiple ways to achieve this. But I want to show you that you can use a label to control the scope. You can declare the label at any scope you want and use the label with break or continue keyword. As you see in the above code, it will exit the entire thing once it finds the word.

go run main.go computer
index 3: "computer"

Go Lang – Printf Cheat Sheet

This is a go lang Printf cheat sheet post. Essentially it is very similar to the one in C. Just like the one in C, Printf really prints the string in a formatted way. It is very convenient to have a cheat sheet since I always forget unless I use it frequently. This mainly focuses on examples.

print type of variable %T

var intNum int
var floatNum float64
var boolVal bool
var strVal string

fmt.Printf("%T\n", intNum)
fmt.Printf("%T\n", floatNum)
fmt.Printf("%T\n", boolVal)
fmt.Printf("%T\n", strVal)

// output
int
float64
bool
string

print int type %d

This prints integer type. It will perform type check and will give you a warning that type doesn’t match. And of course the result format will be odd.

age := 21
fmt.Printf("age: %d\n", age)
fmt.Printf("age: %s\n", age)

// output
age: 21
age: %!s(int=21)

print float %f

%f prints floating numbers. Since this is a floating number, you can control the precision with “.<number>”
Increasing precision means the floating number will be more precise.

floatNum := 224.701
fmt.Printf("num: %f\n", floatNum)
fmt.Printf("num: %.0f\n", floatNum)
fmt.Printf("num: %.1f\n", floatNum)
fmt.Printf("num: %.2f\n", floatNum)
fmt.Printf("num: %.3f\n", floatNum)
fmt.Printf("num: %.4f\n", floatNum)
fmt.Printf("num: %.5f\n", floatNum)

// output
num: 224.701000
num: 225
num: 224.7
num: 224.70
num: 224.701
num: 224.7010
num: 224.70100

print bool %t

male := true
female := false

fmt.Printf("are you male?: %t\n", male)
fmt.Printf("are you femail?: %t\n", female)

//output
are you male?: true
are you femail?: false

print string type %s, %q

Those print the strings. However, there is a difference between them. %s just prints the string itself but %q prints with double quotes.
Note that \n is just an escape sequence providing a new line. This also performs type checks.

name := "Google"
fmt.Printf("%s\n", name)
fmt.Printf("%q\n", name)

// output
Google
"Google"

print any value %v

This prints all the provided values. It’s very convenient but it doesn’t guarantee any type safety. For example, what if you only want to print int instead of string or float? %v will not check anything and print as-is.

name := "Google"
val := 1
floatVal := 1.123
fmt.Printf("%v %v %v\n", name, val, floatVal)

// output
Google 1 1.123

Argument Index

Typically you have to provide a value for each verb in the Printf format string. However, there is an exception to this rule. You can refer to the already provided variable. This is called argument index. Note that [1] refers to the first argument which is “name”. [2] refers to the second argument. Why does the index start from 1? It’s because index 0 of the Printf is the format string.

name := "NY Comdori"
job := "software engineer"

fmt.Printf("%v is a %v. Being %[2]v is fun! Good luck %[1]v!\n", name, job)

// output
NY Comdori is a software engineer. Being software engineer is fun! Good luck NY Comdori!

Go lang – iota and constants

In programming languages such as C++ and Java, there is Enum type which is used frequently. In go language, you can use iota to represent an Enum type.

Let’s take a look at a simple example

Example

Let’s say you want to define variables to represent weekdays. In that case, you probably just want to have integer values for a simple comparison. (You really don’t want to use string to represent the value unless you are printing) Let’s take a look at a version that naively represents the weekdays.

const (
	SUNDAY = 0
	MONDAY = 1
	TUESDAY = 2
	WEDNESDAY = 3
	THURSDAY = 4
	FRIDAY = 5
	SATURDAY = 6
)

// output
fmt.Println(SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY)

0 1 2 3 4 5 6

Now it will perfectly fine because you can use those variables like others. However, it is very tedious to explicitly type all the values because you really don’t care about those. You just want consecutive integers. Here is where iota comes into play to make life better.

What is iota? It is a built-in constant generator that generates consecutively increasing numbers. Let’s take a look at the usage

const (
	SUNDAY = iota
	MONDAY
	TUESDAY
	WEDNESDAY
	THURSDAY
	FRIDAY
	SATURDAY
)

// output
fmt.Println(SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY)

0 1 2 3 4 5 6

With iota, you only need to assign iota once to the place you want to generate. iota always starts from 0 and will increase the number and repeat the same assignment as the previous line. In the example above, SUNDAY will be 0. For MONDAY, iota will repeat itself with the increased number which is 1. It will stop once it reaches the end and the value will be reset to 0 so that it won’t disrupt other constant settings. What happens if you want to use iota from the middle part?

const (
	SUNDAY = -1
	MONDAY = iota
	TUESDAY
	WEDNESDAY
	THURSDAY
	FRIDAY
	SATURDAY
)

// output
fmt.Println(SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY)
-1 1 2 3 4 5 6

You just have to explicitly set the value before the iota usage. iota will start from there. Note that iota value starts from 1 instead of 0.
Why is that? It’s because iota starts from the beginning of the constants.

Blank Identifier

You can use a formula to set a custom value using iota. iota always starts from 0 and if you want a different value, you have to use some expression to do that. Let’s say you want to represent different timezones in constants. You only want to represent three timezones in the U.S. – EST, MST, PST – compared to UTC. For example, EST means the eastern standard time that is -5 hours behind UTC. MST means mountain time that is -7 hours behind UTC. PST means the pacific time that is -8 hours behind UTC. Therefore you want to have your constants represent like this.

const (
	EST = -5
	MST = -7
	PST = -8
)

fmt.Println(EST, MST, PST)
-5 -7 -8

But how can you use iota here? There are two issues here. iota will return a non-negative increasing number but you want to have negative numbers here. The second issue is that the values we want are not consecutive. Let’s tackle the issue one by one. How can we have negative numbers using iota? We can use a formula to manipulate the value.

const (
	EST = -(iota + 5)
	MST
	PST
)

fmt.Println(EST, MST, PST)
-5 -6 -7

You can use a typical mathematical expression when using iota because it just returns a number.

Now, there is still an issue here. We want -5, -7, -8 but actually got -5, -6, -7 because iota only returns consecutively increased numbers. What can we do? Remember that iota will always increase the value in every line. But We certainly don’t want to declare any dummy constant just for that. Blank identifier comes to the rescue. Blank identifier in go is to tell the compiler this is unused variable and ignore it. It is ‘_’.

const (
	EST = -(iota + 5)
	_
	MST
	PST
)

fmt.Println(EST, MST, PST)
-5 -7 -8

Now, note that iota will increase by 1 at line 3. We all know that ‘_’ is a dummy and can just ignore. In MST, it will be set to -7 which is the correct value now.

Conclusion

We have briefly taken a look at iota and constants in go lang. It could be pretty convenient when used properly. Happy coding!

Intro to CSS Grid Layout Part 5

This is intro to CSS grid layout part 5. So far we have taken a look at following topics. It is recommended to take a look if you are not familiar with css grid layout basics.

In this post, I will focus on explaining how to use grid area with area names for positioning grid items with an example. Let’s take a look it.

Example

We have a layout of multiple items. Note that the header is not spanning to the end but the last slot is empty.

HTML Code

This is the html code used for the example

<div class="challenge">
  <div class="header">Header</div>
  <div class="small-box-1">Small box</div>
  <div class="small-box-2">Small box</div>
  <div class="small-box-3">Small box</div>
  <div class="main-content">Main content</div>
  <div class="sidebar">Sidebar</div>
  <div class="footer">Footer</div>
</div>


CSS Code

We have 4 rows and 4 columns which make 16 unit areas. To use area based positioning, you need to define each unit area with an area name. You can decide the name as you prefer. As you can see, grid-template-areas property is defined with 16 names. For example, head is located at the first row and spanning from first to third column. “.” represents an empty slot. After you define the area representation, all you need to do is to specify the area name for each class. Take a look at line 21 and others.

.challenge {
  width: 1000px;
  margin: 30px auto;
  
  display: grid;
  grid-template-rows: 100px 200px 400px 100px;
  grid-template-columns: repeat(3, 1fr) 200px;
  grid-gap: 35px;
  grid-template-areas: "head head head ."
                      "small-box-1 small-box-2 small-box-3 side"
                      "main main main side"
                      "foot foot foot foot";
  
  & > * {
    background-color: orangered;
    padding: 15px;
    color: white;
    font-size: 30px;
    font-family: sans-serif;
  }
  .header {
    grid-area: head;
  }
  
  .small-box-1 { grid-area: small-box-1; }
  .small-box-2 { grid-area: small-box-2; }
  .small-box-3 { grid-area: small-box-3; }
  
  .sidebar {
    grid-area: side;
  }
  
  .main-content {
    grid-area: main;
  }
  
  .footer {
    grid-area: foot;
  }
}

It is very important to note that you have to have a complete area representation. Since you have 16 unit slots (4 rows * 4 columns), you have to have 16 area names in order to use it. It is fairly simple to use for a simple area layout. However, if you have a complex layout, it could be inconvenient to use it. i.e., 10 rows and 10 columns. In such a case, it would be better to use grid lines instead of names.

Intro to CSS Grid Layout Part 4

This is intro to CSS grid layout part 4 continuing from previous posts. This will specifically focus on how to position grid items based on the name of the grid lines. If you are not familiar with CSS grid layout, please refer to these posts here.

In the previous post, we went over how to position grid items based on their grid line numbers. However, it is often hard to read and understand the code when it’s using line numbers. To improve the readability and maintainability, we want to use names for the line numbers. Let’s take a look at them now.

Example

This is the one we are going to build using CSS grid layout.

HTML Code

<div class="challenge">
  <div class="header">Header</div>
  <div class="small-box-1">Small box</div>
  <div class="small-box-2">Small box</div>
  <div class="small-box-3">Small box</div>
  <div class="main-content">Main content</div>
  <div class="sidebar">Sidebar</div>
  <div class="footer">Footer</div>
</div>


CSS Code

.challenge {
  width: 1000px;
  margin: 30px auto;
  
  display: grid;
  grid-template-rows: [header-start] 100px [header-end box-start] 200px [box-end main-start] 400px [main-end footer-start] 100px [footer-end];
  grid-template-columns: repeat(3, [col-start] 1fr [col-end]) 200px [grid-end];
  grid-gap: 35px;
  
  & > * {
    background-color: orangered;
    padding: 15px;
    color: white;
    font-size: 30px;
    font-family: sans-serif;
  }
  .header {
    grid-column: col-start 1 / grid-end;
  }
  
  .sidebar {
    grid-column: col-end 3 / grid-end;
    grid-row: box-start / main-end;
  }
  
  .main-content {
    grid-column: col-start 1 / col-end 3;
  }
  
  .footer {
    grid-column: col-start 1 / grid-end;
  }
}

Let’s first take a look at how grid-template-rows and grid-template-columns are defined. Typically, you would just list width of each row and column and use the line number. However, in each line number position, you can have a list of names to use instead of numbers.

Name for grid-template-rows

Note that row line number 1 is before the first row which is now named header-start. Now, row line number 2 could have multiple names because it is the position where header ends but all other boxes start. That’s why we also added a name box-start at row line number 2. You can follow the similar logic for all other row numbers.

grid-template-rows: [header-start] 100px [header-end box-start] 200px [box-end main-start] 400px [main-end footer-start] 100px [footer-end];

Name for grid-template-columns

There is a difference for columns because it uses repeat with fractional units. Just putting the name before and after the repeat would be incorrect because it will not put names between those columns. We put names in the repeat keyword like this: repeat(3, [col-start] 1fr [col-end]). It means I want to put a name before and after 1fr column. In order to prevent any name conflict, CSS will automatically add numbers starting from 1.

grid-template-columns: repeat(3, [col-start] 1fr [col-end]) 200px [grid-end];

Usage

Now you can define all element classes using names instead of line numbers. I am only going to note one class as an example here. As you can see sidebar class, it is using names. Since the sidebar is the end column of the grid, it uses col-end 3 and grid-end (3 is automatically added by CSS). The row uses box-start and main-end.

.sidebar {
  grid-column: col-end 3 / grid-end;
  grid-row: box-start / main-end;
}


Conclusion

It is very simple to use names instead of line numbers when positioning grid items. And it is actually recommended practice. In the next post, I will explain how to position grid items based on grid area using names.

Intro to CSS Grid Layout Part 3

This is a continuation of intro to css grid layout articles. Please refer to previous articles for declaring grid layout and fractional units in row/column. This post will specifically focus on the positioning and spanning of the grid item. Let’s take a look at the example image and code first.

Example

HTML Code

<div class="container">
  <div class="item item--1">1: Orange</div>
  <div class="item item--2">2: Green</div>
  <div class="item item--3">3: Violet</div>
  <div class="item item--4">4: Pink</div>
  <div class="item item--5">5: Blue</div>
  <div class="item item--6">6: Brown</div>
</div>

As you see in the above image and the HTML code, each item is placed in the order of declaration which is the default positioning of the CSS grid layout. Then, you might ask a question if it’s possible to place an item to a specific location. For example, how do you place the item 1: orange to the location of 5: blue? There are CSS properties that allow you to change the position.

CSS Code

.container {
  background-color: #eee;
  width: 1000px;
  margin: 30px auto;
  
  display: grid;
  grid-template-rows: repeat(2, 150px);
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 60px;
}

.item {
  padding: 20px;
  font-size: 30px;
  font-family: sans-sarif;
  color: white;
  
  &--1 {
    background-color: orangered;
    grid-row-start: 2;
    grid-row-end: 3;
    grid-column-start: 2;
    grid-column-end: 3;
    /*grid-row: 2 / 3;*/
    /*grid-column: 2 / 3;*/
  }
  
  &--2 {
    background-color: green;
  }
  
  &--3 {
    background-color: violet;    
  }
  
  &--4 {
    background-color: pink;
  }
  
  &--5 {
    background-color: blue;
  }
    
  &--6 {
    background-color: brown;
  }
}

Take a look at lines 20-23 in the CSS code. You have two choices to change the position.
1. use grid-<row/column>-<start/end>
2. use grid-<row/column> which is a short hand version

Do you remember there are row/column line numbers when you have CSS Grid? If you are not familiar with the concept, please refer to this article. Basically, there are row/column line numbers and you just need to specify row/column start/end position based on the number.

Looking at the image there are 3 row lines: start of the row grid, middle of the row grid and end of the row grid (1,2,3). There are 4 lines in the column: start of the column grid, 2 middle lines, end of the column grid. After specifying row/column start/end points you will notice that item 1 is now placed where item 5 was.

There are shorthand version of specifying row/column start/end which are commented at line 24,25. There is another shorthand version which is using grid-area but I think it is not really readable and didn’t specify here. You can take a look at the documentation for that.

What if more than one items are to be placed on the same position? Simply the last one will be rendered on top of the first one. The first item will not be shown.

What if you put multiple rows or columns in the grid-row or grid-column? It will simply span to take the specified area. Note that grid-column now has start at 2 and end at 4 which should take space from column 2 to 4.

  &--1 {
    background-color: orangered;
    grid-row: 2 / 3;
    grid-column: 2 / 4;
  }

Note that item 6 is now pushed to new row because item 1 is taking up the space. Even though we only specified 2 rows, CSS grid automatically expands to fit the items which is called implicit grid I will discuss in different post.

Another way of specifying the span is like this. Note that instead of specifying the end column in line 4, you can tell how many lines it should span in this case 2. Another special usage is putting -1 (at line 7) which means to span to the end of the columns.

  &--1 {
    background-color: orangered;
    grid-row: 2 / 3;
    grid-column: 2 / span 2;
    
    /*
    grid-column: 2 / -1;
    */
    
  }

Conclusion

We have taken a look at positioning of the grid item. In next post, I am going to explain how to name grid line numbers to improve readability.

Intro to CSS Grid Layout Part 2

This is intro to css grid layout part 2, continuing from the first post which explained basics of CSS grid layout. This post will explain fractional units which control the width of each grid item.

Example CSS Grid Layout

Example HTML Code

This is the html code used for the example images in the post.

<div class="container">
  <div class="item item--1">1: Orange</div>
  <div class="item item--2">2: Green</div>
  <div class="item item--3">3: Violet</div>
  <div class="item item--4">4: Pink</div>
  <div class="item item--5">5: Blue</div>
  <div class="item item--6">6: Brown</div>
</div>


Example CSS Code

This is the common CSS code used for the example images. I will specify more properties separately when necessary. For more explanations about rows, columns and gap properties, please take a look at the first post.

.container {
  background-color: #eee;
  width: 1000px;
  margin: 30px auto;
  
  display: grid;
  grid-template-rows: repeat(2, 150px);
  grid-template-columns: repeat(3, 200px);
  grid-gap: 30px;
}

.item {
  padding: 20px;
  font-size: 30px;
  font-family: sans-sarif;
  color: white;
  
  &--1 {
    background-color: orangered;
  }
  
  &--2 {
    background-color: green;
  }
  
  &--3 {
    background-color: violet;    
  }
  
  &--4 {
    background-color: pink;
  }
  
  &--5 {
    background-color: blue;
  }
    
  &--6 {
    background-color: brown;
  }
}


Fractional Units

We have defined a two-dimensional grid with two rows (width 150px) and three columns (width 200px). However, as you can see the left over space (gray color), the grid is not filling up the container width. Fractional units become useful to fill up the space just like flex: 1 property. Note that I only modified the necessary property for readability (you will still need the common code along with the modified one)

.container {
  grid-template-columns: repeat(2, 200px) 1fr;
}

Now, we have two columns of width 200px and the last column just grows to fill all the available space in the container.

What if you want to have all the columns grow equally instead of fixed width? You just need to specify the fr in the repeat like this.

.container {
  grid-template-columns: repeat(3, 1fr);
}

Note again that 1fr is a fraction of each available space. It means 2fr will have double size of 1fr in the container. You can also think of it as this way – the entire width will be divided into each fraction based on the specified ratio. You can use mix of %, px, or fr. For example, if you put the code as the following, the first column will have the 50% of the entire width and the rest of columns will be divided based on specified fr.

.container {
  grid-template-columns: 50% 1fr 2fr;
}

One thing to note is the gap size when using % or px. % or px do not take the gap as part of their size. They take the specified width. However, fractional units count the space after subtracting the gaps from the available space. Note the difference between the two images below – gap increase from 30px to 60px. The first column – width 50% – stays same but the width of the others decrease as gap size increased.


Conclusion

In this post, we went over fractional units which control the width of each grid item. For defining CSS grid, please take a look at the first post. In the next article, I am going to explain the positioning of each grid item.

Intro to CSS Grid Layout Part 1

This post is an intro to CSS grid layout part 1. You can use CSS Grid to easily build a two-dimensional grid-based layout. This is the first part of the article which will specifically focus on the basic properties.


CSS Grid Layout Example

The above image represents basics of CSS grid layout. It has two rows and three columns. Each brown box is called a grid item. There is a gap between the items which is called a gutter.


Grid Container

It is the container of the grid. You can declare the container by calling this in the CSS file.

.container {
    display: grid;
}


Row/Column

Row and column of the container can be specified by calling the following after display: grid

.container {
  grid-template-rows: 150px 150px;
  grid-template-columns: 150px 150px 150px;    
}

The above declares two rows and three columns. Each row/column has width of 150px. However, it is a bit inconvenient to specify all the rows and columns separately. For that you can use the keyword repeat.

.container {
  grid-template-rows: repeat(2, 150px);
  grid-template-columns: repeat(3, 150px);
}

The above code is exactly same as the first one. If you want to have different width for certain row or column, you can just specify it like this.

.container {
  grid-template-rows: repeat(2, 150px);
  grid-template-columns: repeat(2, 150px) 200px;
}

Now you have 2 rows with the same width but 3 columns of which first 2 columns have 150px and the last column has 200px.

Note the numbers around the row and column (row: 1,2,3 and column:1,2,3,4) are row lines and column lines.


Gap (gutter)

The space between each grid item. You can define the row/column gap separately or the same depending on the property.

.container {
  grid-row-gap: 30px;
  grid-column-gap: 50px;
}

The above code has 30px for row gap and 50px for column gap. Row gap is the space between two rows (there are only two rows).
Column gap is the spaces between three columns (there are only three columns)

If you would like to have the same space for all the gaps, you can use this property.

.container {
  grid-gap: 30px;
}


Conclusion

We have taken a look at very basics of CSS grid layout – declaring two-dimensional grid with rows and columns. In next post, I will go over more of CSS grid. fractional units, positioning of grid items

CSS – Intro to Flexbox Part 3

This is the continuation of CSS – intro to flexbox part 3. Previous posts explained what flexbox is and conceptual things (part 1) and flexbox container properties and examples (part 2). This post will focus on explaining the properties of flex items and examples for them. Since flex items properties are only applicable to the specified item, I posted the HTML, CSS code again for easier understanding. Please pay special attention to the classes such as i2, i4 that are specific to the item.

HMTL Code

<div class="container">
  <div class="item">1</div>
  <div class="item i2">2</div>
  <div class="item">3</div>
  <div class="item i4">4</div>
  <div class="item">5</div>
</div>


CSS Code

.container {
  background-color: #ccc;
  display: flex;;
  justify-content: space-between;
  align-items: center;
}

.item {
  background-color: orangered;
  padding: 30px;
  margin: 20px;
  color: #fff;
  font-size: 40px;
}

.i2 {
  height: 200px;
}


align-self: flex-end

This property aligns the item along the cross axis and at the end of the cross axis. As you see in the example, all the items are located at the center due to align-items: center but only item 4 is located at the end of the cross axis. Note that it might look weird since item 2 has a different height. But the item 2 is still aligned in the center of the cross axis.

.i4 {
    align-self: flex-end;
}


align-self: flex-start

This one is the opposite of the flex-end. You will see the item 4 is now aligned at the start of the cross axis.

.i4 {
    align-self: flex-start;
}


align-self: stretch

This property stretches the flex item to fill the entire container. You will see the height of item 4 is now the same as item 2 since it is the max height item – 200px.

.i4 {
    align-self: stretch;
}


order: <integer>

The order property decides the order of the flex items in the container. By default, all the items have 0 for the order value. In this example, I put -1 to item 4, and now it is the first one to be placed among all the items because -1 < 0 and flexbox always display the item based on the order (lowest order first).

.i4 {
    align-self: flex-end;
    order: -1;
}


What if you put -2 order value to item 3? Since -2 < -1, the item 3 will be placed before the item 4.


flex-grow: <integer>

The flex-grow property indicates the growth of each item. As you can see in the example below, setting flex-grow: 1 made all the items grow as much as possible. The space between the items is because of the margin property.

.item {
  /* skipped all the common properties since they are defined above */
  flex-grow: 1;
}


Note that the number is to indicate the relation compared to others. Just for the above example, it doesn’t matter which number you put because there is only one flex-grow in the item class. Then, what happens if we put flex-grow: 2 to item class such as i2?

.i2 {
  height: 200px;
  flex-grow: 2;
}


Do you see that the item 2 has double width of other items? it’s because the item2 has flex-grow: 2 which is twice of the other items – flex-grow: 1.

flex-basis: <% or px>

You can set a width of a flex item by using flex-basis property. When you deal with flex items, you usually use flex-basis instead of width property. In the example below, the item 2 now occupies 40% of the container.

.i2 {
  height: 200px;
  flex-basis: 40%;
}


flex-shrink: <integer>

Unlike flex-grow, flex-shrink tells the flexbox how the items should shrink when the viewport size change. I didn’t paste the example picture here as it was bit hard to capture the screenshot to indicate the viewport size. However, I still pasted the code example which you can try in the codepen.

.i2 {
  height: 200px;
  flex-basis: 300px;
  flex-shrink: 1;
}


The item 2 has now the fixed width in the container and flex-shrink is allowed (value 1). As you decrease the viewport width you will see the item shrinks. What happens if you disable the shrink? (flex-shrink: 0). Then, you will see that the item 2 will always keep the width of 300px.


flex: <grow> <shrink> <basis>

We have taken a look at the three flex item properties – grow, shrink, basis. However, it is actually more recommended to use flex property instead of others. It is the shorthand of all and very convenient to use. And using flex property instead of those three are is considered a best practice.

.i2 {
  height: 200px;
  flex: 0 0 300px;
}

.i4 {
  order: 2;
  flex: 1;
}

Item 2 doesn’t grow and shrink but has a fixed width of 300px. So the items 1,2,3,5 are rendered first. Then, item 4 has flex-grow enabled so it takes the remaining available space after 1,2,3,5. If you decrease the viewport width on your screen, you will see item 4 will shrink but not item 2. However, if you allow shrinking in item 2 (flex: 0 1 300px) then you will see item 4 shrink first because it has the largest space followed by item 2.


Conclusion

We have completed a long journey of taking a look at basics of flexbox. There are a ton of more stuff and will try to write in different posts.

CSS – Intro to Flexbox Part 2

This is the continuation of the post – css intro to flexbox part 1. Part 1 mostly focused on explaining conceptual things. In this post, I am going to focus on showing examples for each flexbox property. Note that all the other common css code is in part 1. I wrote necessary code only for each property.

justify-content

As explained in part 1 post, justify-content tells you how the flex items should be aligned along the main axis.

justify-content: center

justify-content:center aligns the flex items in the middle of the container but doesn’t do anything for the space between the items because space is defined by the margin.

.container {
    justify-content: center;
}


justify-content: space-between

Space is evenly distributed between flex items. Flexbox automatically calculates all the spaces and positions for each item. Space between the items will be automatically adjusted if the width of the container changes.

.container {
    justify-content: space-between;
}


justify-content: space-around

space around puts the same amount of space for both left and right side of each item. You will see that the space between item 1 and 2 are double of the left space of item 1. The difference between space-between and space-around is that space-between only evenly distributes the space between the items but space-around puts all the space equally for both left/right side.

.container {
    justify-content: space-around;
}


justify-content: space-evenly

space-evenly puts equal space to all sides. As you can see all the spaces are same here. It ensures all the spaces between the elements and side of the elements are same.

.container {
    justify-content: space-evenly;
}


justify-content: flex-end

flex-end puts all the elements to the end. Note that main-axis here is horizontal from left to right that all the elements are placed on the right side.

.container {
    justify-content: flex-end;
}


justify-content: flex-start

This is the default option which places all the items to the start (main axis from left to right) which is left side.

.container {
    justify-content: flex-start;
}


align-items

align-items tells how the flex items should be aligned along the cross axis which is perpendicular to main axis. To show the example, I need to have different height for one of the item.

New HTML Code for align-items example

<div class="container">
  <div class="item">1</div>
  <div class="item i2">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
</div>

New CSS Code for align-items example

.i2 {
  height: 200px;
}


align-items: flex-start

Note again align-items will align the items along cross axis. flex-start will align all the items to the start of the axis which is top in this case. It might be little hard to see at first time. But take a closer look and you will see all the items are aligned at the top which is the start of the cross axis

.container {
    align-items: flex-start;
}


align-items: flex-end

flex-end now will place all the items at the end of the cross axis which is the bottom.

.container {
    align-items: flex-end;
}


align-items: center

As you can already guess, center will place all the items on the center of the cross axis.

.container {
    align-items: center;
}


align-items: stretch

This is the default mode which stretches all the items to the max of flex items. Since it’s default, you don’t need to specify at all.

.container {
    align-items: stretch;
}


align-items: baseline

baseline will align the items based on the text in the flex item. For the example, let me add another class – increasing the font size.

New HTML Code

note that i4 class is added to 4.

<div class="container">
  <div class="item">1</div>
  <div class="item i2">2</div>
  <div class="item">3</div>
  <div class="item i4">4</div>
  <div class="item">5</div>
</div>
New CSS Class
.i4 {
  font-size: 70px;
}

.container {
  align-items: baseline;
}


What happens if flex-direction: column?

It changes the main axis from top to bottom and cross axis from left to right. In this case, you will see all the items are in the center of horizontal line due to align-items: center (see the code below). justify-content: center makes sure all the items are centered vertically here.

.container {
    flex-direction: column;
    justify-content: center;
    align-items: center;
}


Conclusion

We have taken a look at how flex container properties work. I will continue to explain flex item properties in different post. For conceptual explanation, please take a look at part 1. And for more examples of flex items please take a look at part 3