To vertically align an image inside a <div>
, you can use CSS to control the image's alignment within the container. There are several ways to achieve vertical alignment, but one common method is to use the CSS flexbox
or grid
layout. Here's an example using flexbox
:
HTML:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Vertical Align Image</title>
</head>
<body>
<div class="container">
<img src="image.jpg" alt="Image">
</div>
</body>
</html>
CSS (styles.css):
css
body {
margin: 0;
padding: 0;
display: flex; /* Center the container horizontally and vertically */
justify-content: center;
align-items: center;
min-height: 100vh; /* Ensure full viewport height */
}
.container {
text-align: center; /* Center the content horizontally */
}
img {
vertical-align: middle; /* Vertically align the image within the container */
}
In this example:
We use
display: flex;
on thebody
to center the container both horizontally and vertically within the viewport usingjustify-content
andalign-items
.Inside the container, we set
text-align: center;
to center the content (in this case, the image) horizontally.To vertically align the image, we apply
vertical-align: middle;
to theimg
element. This will vertically center the image within the container.
With this CSS, the image will be both horizontally and vertically centered within the container. You can replace "image.jpg"
with the path to your image file, and adjust the container and image sizes as needed.
Comments
Post a Comment