Images play a crucial role in the functionality of web applications. While overloading a web application with images is discouraged, it remains essential to incorporate them strategically where needed. CSS provides the means to manage and adjust the presentation of images within web applications.
Aligning an image involves placing it in the center, left, or right positions on a webpage. The alignment can be achieved by utilizing the float property or the text-align property for images.
If the picture is contained within the div element, we can leverage the text-align attribute to position the image within the div.
Example
In this instance, we are centering the images by applying the text-align property. The images are contained within a div container.
<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 2px solid red;
}
img{
height: 250px;
width: 250px;
}
#left {
text-align: left;
}
#center {
text-align: center;
}
#right{
text-align: right;
}</style>
</head>
<body>
<div id ="left">
<img src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image">
</div>
<div id ="center">
<img src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image">
</div>
<div id ="right">
<img src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image">
</div>
</body>
</html>
Output
Using float property
The CSS float attribute functions as a layout property, enabling the alignment of an element to the left or right side of its container. This positioning creates space for other elements to flow around it, commonly applied in scenarios involving images and page layouts.
Elements can be floated exclusively in a horizontal direction. This limits the floating options to either left or right, with no option to float elements vertically. When an element is floated, it can be positioned as far left or right as the available space allows. Essentially, this indicates that a floated element can be positioned at the furthest left or right side of its containing element.
Example
<!DOCTYPE html>
<html>
<head>
<style>
img{
height: 200px;
width: 250px;
border: 7px ridge blue;
}
#left{
float: left;
}
#right{
float: right;
}</style>
</head>
<body>
<img src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image" id ="left">
<img src="https://placehold.co/400x300/1abc9c/ffffff?text=Sample+Image" id="right">
</body>
</html>
Output