I made an html document and I put an <img>
tag in it.
I want to align center the image using margin-left:auto
and margin-right:auto
but it not working. Here is the HTML code:
<html>
<head>
<style>
img {
margin-left:auto;
margin-right:auto;
}
</style>
</head>
<body>
<img src="http://www.w3schools.com/images/lamp.jpg" />
</body>
</html>
what is wrong?
You need to change your <img>
to a block element. Add display: block;
to your CSS and it will center.
img{
margin-left:auto;
margin-right:auto;
display: block;
}
<img>
tags by default are inline-block, which doesn't center when using the margin trick.
Also, instead of having both margin-left
and margin-right
you can just use margin
You don't have to, but I always like having as few lines of code as possible.
img{
margin: 0 auto;
display: block;
}
You could do it like that with CSS, but HTML also has a build-in option for that. Good luck!
<html><body><img src="IMG SRC HERE" align="center/right"></html></body>
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.