Here, we will use flex property to align text vertically and horizontally without any collapse. The flex property is basically added to the css standards for space distribution and element alignment. It is very easy to write, responsive and mobile friendly. The flex property is used to position the child elements within the main container. So the margin doesn’t collapse with the content margins.
In the below example, we will use the flex property to set the content to vertical and horizontal alignment. By setting the following three properties to the text can be aligned vertically/horizontally. This example also shows how to position the three different directions (center, left and right) of the elements.
- align-items
- justify-content
- Flex-direction
Example
Follow the below example to learn flexbox property.
<!DOCTYPE html>
<html lang="en">
<head>
<title>How to align text vertically/horizontally inside a flexbox using css</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.flex-display{
display: flex;
}
.flex-box{
width: 100%;
min-height: 350px;
background: #B2BEB5;
margin: 20px;
padding: 20px;
}
.text-vertical-center{
display: flex;
align-items: center;
justify-content: center;
}
.text-vertical-left{
display: flex;
align-items: start;
justify-content: start;
}
.text-vertical-right{
display: flex;
align-items: end;
justify-content: end;
}
</style>
</head>
<body>
<div class="flex-display">
<div class="flex-box text-vertical-center">
<div>
<h2>Example-1</h2>
<h3>Align text using Flexbox property</h3>
</div>
</div>
<div class="flex-box text-vertical-left">
<div>
<h2>Example-2</h2>
<h3>Align text using Flexbox property</h3>
</div>
</div>
<div class="flex-box text-vertical-right">
<div>
<h2>Example-3</h2>
<h3>Align text using Flexbox property</h3>
</div>
</div>
</div>
</body>
</html>
Popular Posts
- Show / Hide div based on dropdown selected using jQuery
- Infinite Scrolling on PHP website using jQuery and Ajax with example
- How to Convert MySQL Data to JSON using PHP
- Autosuggestion Select Box using HTML5 Datalist, PHP and MySQL with Example
- Custom Authentication Login And Registration Using Laravel 8
- Slick Slider Basic With Example
- Image Lazy loading Using Slick Slider
- How to change date format in PHP?
- Adaptive Height In Slick Slider
- php in_array check for multiple values
- Slick Slider Center Mode With Example
- JavaScript Multiple File Upload Progress Bar Using Ajax With PHP
- How to Scroll to an Element with Vue 3 and ?
- Google Login or Sign In with Angular Application
- Slick Slider Multiple Items With Example