CSS tips: Vertical alignment of image and text in a DIV

├Źndice
  1. Introduction
  2. Method 1: Flexbox
  3. Method 2: Absolute Positioning
  4. Conclusion

Introduction

Aligning images and text vertically in a DIV using CSS can be challenging, especially when dealing with different screen sizes and resolutions. In this article, we will provide some tips on how to achieve vertical alignment of image and text in a DIV with ease.

Method 1: Flexbox

Flexbox is a great solution for aligning elements vertically and horizontally within a container. To use Flexbox, first, we need to set the display property of the parent container to flex. Then, we can use the align-items property to align the items vertically. Here's an example:

<div class="container">
  <img src="image.jpg" alt="Image">
  <p>Text</p>
</div>

.container {
  display: flex;
  align-items: center; /* Align items vertically */
}

Method 2: Absolute Positioning

Absolute positioning is another way to vertically align elements within a container. To use absolute positioning, we need to set the position property of the parent container to relative. Then, we can use the position and transform properties to position the child elements vertically. Here's an example:

<div class="container">
  <img src="image.jpg" alt="Image">
  <p>Text</p>
</div>

.container {
  position: relative;
}

.container img,
.container p {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

Conclusion

Vertical alignment of image and text in a DIV can be achieved using Flexbox or absolute positioning. Both methods have their own advantages and disadvantages, so choose the method that works best for your particular situation. With these tips, you can now easily align your images and text vertically in your web pages.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information