Originally posted here!
To make HTML elements in horizontal order or row-wise that are responsive to the screens, we can use the CSS display
property and set its value to flex
, then we can use the property flex-direction
and set its value to row
, and finally, we can use the flex-wrap
property and set its value to wrap
. These values should be applied to the parent element of the children elements where you want this to take place.
For example, let's say we have three red color boxes with 200 * 200
dimensions (width * height).
The HTML code would look something like this,
<html>
<body>
<!-- Three `red` color boxes -->
<div>
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
</div>
<!-- Styles for the boxes -->
<!--
`margin` of `2px` is applied to
make some gap within the elements
-->
<style>
.box {
width: 200px;
height: 200px;
background-color: red;
margin: 2px;
}
</style>
</body>
</html>
The webpage now looks like this,
As you can see that we have defined three red
background colors div
and applied a width of 200px
and a height of 200px
. If you look closely, you can also see a parent div
that is enclosing all these boxes. This is where we have to apply the CSS properties to make it horizontal order or row-wise.
Let's add a class of parent
to the parent div
element and apply the display: flex;
, flex-direction: row;
and the flex-wrap: wrap;
properties to it.
It can be done like this,
<html>
<body>
<!-- Three `red` color boxes -->
<!--
add a class name of `parent` to the parent
`div` to apply styles to it.
-->
<div class="parent">
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
</div>
<!-- Styles for the boxes -->
<!--
`margin` of `2px` is applied to
make some gap within the elements
-->
<!--
adding `display: flex`, `flex-direction: row`
and `flex-wrap: wrap` property to make it in horizontal order.
-->
<style>
.box {
width: 200px;
height: 200px;
background-color: red;
margin: 2px;
}
.parent {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
</style>
</body>
</html>
Now the webpage looks like this,
Now let's understand what just happened. The display: flex;
property sets the parent div
element into a flexbox container, and the flex-direction: row
property made the div take up the entire available width of the screen by making the elements flow in the row
direction and finally the flex-wrap: wrap;
property allows the three red color boxes to go into the second line if the available width is too low.
The flex-wrap: wrap
property made the three boxes to be responsive to the screen.
A visual representation of the webpage is shown below,
We have successfully made the 3 boxes flow in the horizontal direction as well as making them responsive. Yay π₯³!
See the above code live in the codesandbox.
That's all π.
Top comments (0)