Developing a layout using HTML and CSS
Organizing the DOM and styling it. We can study this by recreating following example.
Developing the heading
Take the heading Recent Transactions. It is aligned to left side and three dots to right.
First step is arranging your html.
As the DOM is tree and everything is boxes in html. First think like arranging the bigger box and inside that smaller boxes.
In the above diagram the outer indicates the whole container. The text and three dots are present side by side are put in one more container. The DOM tree is designed so we can control the DOM’s easily.
Achieving the alignment through float : right
This is kind of old school. We can achieve it easily using float but this cause layout to distort when the width of the container is less. The three-dots will wrap around. Now a days the usage of float is becoming less.
.three-dots{
float:right;
}
Achieving it through inline-blocks and widths
The style inline-block helps you to set up width for any element without introducing a new line.
We can add the set up the inline-block to the label and three dots and set up the widths to percentages.
.three-dots {
width:10%; display : inline-block;
}.heading {
width:90%; display : inline-block;
}
This also has issues like width 100% might be overflow and going to next line. It won’t be dynamic in future as we keep on adding more number of elements.
Achieving it through flex
All the children of the display flex has displayblock property and grows width flexibly. The width can be controlled by flex-grow and flex-shrink.
.transactions-box .transactions .three-dots {
text-align: right;
flex-grow: 0;
flex-shrink: 0;
width: 24px;
}.transactions-box .transactions .heading {
flex-grow: 1;
}
Here we made transactions heading grow flexibly using flex-grow:shrink, and we restricted the icon size using flex-grow and flex-shrink. So far this seems to be more sensible approach.
Arranging the body of the transactions
We have to develop the following list item.
We can divide the DOM into the following blocks. The outer div is a flex so it will allow all the child to have same height and have three divisions.
We can divide into the widths of 20%, 50% and 20%.
The first image has to be placed exactly at the center with respect to width and height. We can use inline-flex , justify-content and align-items for this.
.transactions-box .box .user {
display: inline-flex;
justify-content: center;
align-items: center;}
We can use div blocks for the second item so they will appear in two lines.
We can keep the third item as is.
Conclusion
The take away are
- To control a group of elements place them in a div block
- Flex is robust and has more control over the layout
- Its good to keep the DOMs flexible so we can add more elements in future.