In this tutorial, you will learn how to align text and images on the same line in CSS. You can achieve this using several methods in CSS, and we’ll discuss two of the most common, namely flex container and inline-block display.
Using Flex Container
Step 1: Create the HTML Structure
First, you need to create the HTML structure containing the text and image elements you want to align in the same line.
1 2 3 4 |
<div class="flex-container"> <img src="path/to/your/image.jpg" alt="Your Image Description" /> <p>This is an example text to be aligned with the image.</p> </div> |
The <div>
element with the class “flex-container” will be the container for both the <img>
and the <p>
elements.
Step 2: Add CSS for Flex Container
To align the <img>
and <p>
elements, apply the display: flex
property to the “flex-container” class.
1 2 3 |
.flex-container { display: flex; } |
Using Inline-Block Display
Step 1: Create the HTML Structure
Similar to the previous method, first create the HTML structure containing the text and image elements.
1 2 3 4 |
<div class="inline-container"> <img class="align-inline" src="path/to/your/image.jpg" alt="Your Image Description" /> <p class="align-inline">This is an example text to be aligned with the image.</p> </div> |
Notice that we added the class “align-inline” to both the <img>
and <p>
elements for styling purposes.
Step 2: Add CSS for Inline-Block Display
To align the <img>
and <p>
elements, apply the display: inline-block
property to the “align-inline” class.
1 2 3 |
.align-inline { display: inline-block; } |
Full Code
Here’s the full code including both the HTML and CSS for the two methods explained above:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<style> .flex-container { display: flex; } .align-inline { display: inline-block; } </style> <!-- Using Flex Container --> <div class="flex-container"> <img src="image.jpg" alt="Your Image Description" /> <p>This is an example text to be aligned with the image.</p> </div> <!-- Using Inline-Block Display --> <div class="inline-container"> <img class="align-inline" src="image.jpg" alt="Your Image Description" /> <p class="align-inline">This is an example text to be aligned with the image.</p> </div> |
Conclusion
In this tutorial, you learned how to align text and images on the same line in CSS using both the flex container and inline-block display methods. Now you can implement these techniques to create a visually appealing layout for your website.