Unlock the Power of Flexbox: A Comprehensive Guide
What is Flexbox?
Flexbox, or the CSS Flexible Box Module, revolutionized the way developers design and build responsive web pages and applications. Introduced in 2009, it has become the go-to layout system for modern web development. With flexbox, you can easily arrange web components and elements without affecting the underlying markup.
Designing a UI with Flexbox
Let’s create a simple calculator interface using flexbox. We’ll start by creating an HTML file, calc.html
, and adding basic HTML tags.
<!DOCTYPE html>
<html>
<head>
<title>Calculator (Flexbox)</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
</body>
</html>
Adding a Flex Container
Next, we’ll add a container that will stretch the width of the body and place its items in the center.
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
Adding Content to a Flex Container
Now, let’s add a wrapper div inside the container. This wrapper will hold the calculator elements.
<div class="wrapper">
</div>
.wrapper {
width: 500px;
display: flex;
flex-wrap: wrap;
}
Laying Out the Screens
We’ll add two screens: the input screen and the result screen. Each screen will be rendered in a separate column.
<div class="screen input-screen">
</div>
<div class="screen result-screen">
</div>
.screen {
background-color: #f0f0f0;
width: 200px;
height: 100px;
font-size: 24px;
border: 1px solid #ccc;
padding: 10px;
}
Adding Elements to a Flexbox Layout
Next, we’ll add buttons to our flexbox layout.
- 1, 2, and 3 in one column
- 4, 5, 6, and + in another column
- 7, 8, 9, and * in yet another column
- CLR, 0, =, and / in another column
<div class="button-column">
<button>1</button>
<button>2</button>
<button>3</button>
</div>
<div class="button-column">
<button>4</button>
<button>5</button>
<button>6</button>
<button>+</button>
</div>
Styling Elements in Flexbox
Let’s add some styling to our button elements.
.button {
border-bottom-width: 2px;
border-top-width: 2px;
border-right-width: 2px;
width: 50px;
font-weight: bold;
font-size: 24px;
border-style: solid;
text-align: center;
}
Making a Flexbox Layout Responsive
Finally, we’ll make our calculator UI responsive using the @media
query CSS code.
@media (max-width: 500px) {
.wrapper {
width: 300px;
}
.container {
flex-direction: column;
}
.column {
width: 100%;
}
}
The Finished Product
Our calculator UI is now complete and responsive! We’ve successfully used flexbox to design a simple yet functional calculator interface. With flexbox, we can easily create complex layouts without writing extensive CSS code.