Centering an image - A Smarter Way To Learn HTML & CSS (2015)

A Smarter Way To Learn HTML & CSS(2015)

27
Centering an image

Let’s create a class for centering images. I’m going to give it a ridiculous name, to remind you that class names are made up.

img.smack-in-the-middle {
display: block;
margin-left: auto;
margin-right: auto;
}

auto tells the browser to split the left and right margins equally. The result is a centered image.

Here’s the HTML.

<img class="smack-in-the-middle" src="images/founder.jpg" alt="Our founder" width="55" height="85">

Note that in the HTML above class comes before src and all the other specifications. This isn’t strictly necessary, but I’ll ask you to follow the convention when you do the exercises.

An alternative way to code the styling:

img.smack-in-the-middle {
display: block;
margin: 0 auto 0 auto;
}

In your CSS file code a class of images that centers. In your HTML file add a third loris image and assign it this class. Save the files and display the page.

Sample CSS code is at:
http://asmarterwaytolearn.com/htmlcss/practice-27-1.html.

Sample HTML code is at:
http://asmarterwaytolearn.com/htmlcss/practice-27-2.html.

Find the interactive coding exercises for this chapter at:
http://www.ASmarterWayToLearn.com/htmlcss/27.html