There are two ways we will accept you center aligning your images on a page.
In both cases the <img>
tag is inside a block. This is one
description, but more information can also be found
here.
Which ever way you choose, be consistent in your code.
text-align
Recall that an <img>
is both an inline AND a block element. It is because, if inside a block element, it can be aligned using a
text-align
property on the parent.
This is an example of an image centered using
text-align
on the <div>
parent container. But remember in this case, all items in the parent will be center aligned.
/* in the css file */
#centeraligndiv {
text-align: center;
}
<!-- in the html file -->
<div id="centeraligndiv">
<img src="img/jack.jpg" alt="Jack the cat" />
</div>
margin: auto
Here the <img>
tag is a block element. Because it is a
block element, it it can be aligned by having the browser put equal margins
on both sides of the block using the margin-left: auto
and
margin-left: auto
properties.
This is an example of an image centered using margin-left:auto;
and margin-right:auto;
/* in the css file */
.blockcenter {
display: block;
margin-left: auto;
margin-right: auto;
}
<!-- in the html file -->
<div>
<img class="blockcenter" src="img/jack.jpg" alt="Jack the cat">
</div>
Although you may see this in other people's code this it NOT the
way to align an image for CSE 154. in this case the
<img>
tag is outside of a block tag.
/* in the css file */
.blockcenter {
display: block;
margin-left: auto;
margin-right: auto;
}
<!-- in the html file -->
<img class="blockcenter" src="jack.jpg" alt="Jack the cat">