简体   繁体   中英

Div Image not centered vertically and horizontally?

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> 

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

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>

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> 

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>

Try changing left:50% to left:43% . That should get you where you want to be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM