Reputation: 11
My image is not centering with the heading at the top no matter what I try. If anyone can provide me with a code correction it would be greatly appreciated. Thanks in advance.
img {
position: absolute;
top: 50%;
left: 50%;
width: 675px;
height: 418px;
margin-top: -250px;
/* Half the height */
margin-left: -250px;
/* Half the width */
}
body {
background-color: black;
}
h1 {
color: white;
text-align: center;
}
p {
color: white;
font-family: verdana;
font-size: 20px;
}
<h1>Text</h1>
<div class="img">
<img src="rsz_damon600.png">
</div>
Upvotes: 0
Views: 1237
Reputation: 3374
You can simple do it like this. Place the image inside a div element. Then set margin for div as auto. :)
<div name="my_div"style="margin:auto;">
<img src="" id="" />
</div>
Upvotes: 0
Reputation: 1
Try changing left:50%
to left:43%
. That should get you where you want to be.
Upvotes: -1
Reputation: 1238
you should set margin-top and margin-left as half the size of width and height.
or if you don't know the size of element,you can use
transform: translate(-50%, -50%);
to center it both vertically and horizontally
img {
position: absolute;
top: 50%;
left: 50%;
/* width: 675px;
height: 418px; */
transform: translate(-50%, -50%);
}
another method:
img {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
this is a guide
Upvotes: 1
Reputation: 2930
Use css trick transform: translate(-50%, -50%)
:
img {
position: absolute;
top: 50%;
left: 50%;
width: 675px;
height: 418px;
transform: translate(-50%, -50%);
}
body {
background-color: black;
}
h1 {
color: white;
text-align: center;
}
p {
color : white;
font-family: verdana;
font-size: 20px;
}
<style>
</style>
<body>
<h1>Text</h1>
<div class="img">
<img src="http://www.motorverso.com/wp-content/uploads/2015/01/iNFINITI-q60-1_1280x792-675x418.jpg">
</div>
</body>
Upvotes: 0
Reputation: 101
Try:
<!DOCTYPE html>
<html>
<head>
<title>HTML Reference</title>
<style>
img {
display: block;
margin: 0 auto;
}
body {
background-color: black;
}
h1 {
color: white;
text-align: center;
}
p {
color : white;
font-family: verdana;
font-size: 20px;
}
</style>
</head>
<body>
<h1>Text</h1>
<div class="img">
<img src="rsz_damon600.png">
</div>
</body>
</html>
Upvotes: 1