Reputation: 1
I've tried to center a image in css but my code wont work.
img.center {
display: block;
margin-left: auto;
margin-right: auto;
}
<img src="mw3.gif" />
Upvotes: 0
Views: 1291
Reputation: 3089
Just Use: (Remove .center)
img{
display: block;
margin-left: auto;
margin-right: auto;
}
img{
display: block;
margin-left: auto;
margin-right: auto;
}
<img src="http://s.imgur.com/images/imgur.gif">
Upvotes: 1
Reputation: 268
There are more than one ways of centering things in CSS, If you wanna learn about all the possible ways of centering elements in CSS then checkout this detailed article on how to center things in CSS.
Upvotes: 0
Reputation: 138
The problem is that your css is not selecting your the img
element. The css selector you are using is looking for an img
element with the class of center
. You can correct this by either 1) removing the .center
from your css selector so that the selector is just img
like this:
<img src="mw3.gif" class="center" alt="MW3">
img{
display: block;
margin-left: auto;
margin-right: auto;
}
or 2) by adding the center
class to your img
tag like this.
<img src="mw3.gif" alt="MW3">
img{
display: block;
margin-left: auto;
margin-right: auto;
}
Take note of the alt
attribute in the <img>
tags. This attribute is required by the W3C to validate the markup of an <img>
element.
The W3C spec for the img
element regarding the alt
attribute can be found here. Look under Section (4.7.1.1.2).
Upvotes: 1
Reputation: 5135
First let's understand the problem here.
Your HTML is :
<img src="mw3.gif">
and CSS is :
img.center {
display: block;
margin-left: auto;
margin-right: auto;
}
Now, what the img.center
class in the CSS does is that it targets an img
tag having the class "center"
. Now, if you observe you code, the img
tag does not have any class attached to it. So, obviously, the class won't be applied!!!
Now that we know what the problem is, let find the solution :
There are actually 2 solutions here. Use the one that makes the most sense in your case.
You can either assign the img
tag a class of "center"
or you can rename the CSS class to target the img
tag i.e.
Solution 1:
Add class "center"
to img
tag :
<img src="mw3.gif" class="center">
img.center {
display: block;
margin-left: auto;
margin-right: auto;
}
Solution 2 :
Modify the CSS class to target the img
tag :
<img src="mw3.gif">
img {
display: block;
margin-left: auto;
margin-right: auto;
}
NOTE : Its a good practice to use the alt property of the img
tag. The alt
attribute specifies an alternate text for the image, if the image cannot be displayed.
Hope this helps!!!
Upvotes: 2
Reputation: 25
try to put an id for the img and call the css stylesheet with that id, then try with margin: auto; only
Upvotes: 0