HTML and Centering Block Elements

Someday, I’ll eventually figure out how to properly position elements on a web page. Always seems like when I think I know what I’m doing, and then I get something that I just can’t seem to display where I want it to on a page.

Case in point, I was trying to center a <section> element that contained three images side-by-side horizontally. Had no issues getting the images to display how I wanted them in the element; but didn’t seem to matter what I did, I couldn’t get the <section> to center. Did some digging and found the most common answer I came across was to use this CSS style for the block elements like sections:

margin:auto;

So, I added this to the style for my <section> element containing the photos, and nothing. After looking at a few other examples, it finally clicked. Technically, my <section> element was “centered”. It just happened to be the full width of the page with the images left justified. Without defining a set width for the block element, it defaults to the full width of the page, not what is in it.

Sure, I could have tried to center the images within the block element, but still figured centering the block element would be easier. So, I set a defined a width for my <section>, just enough so the images remained side-by-side, and bingo. All three images are now centered in the page.

section.imgcenter {
    width:775px;
    margin:auto;
}

Granted, I then came across https://www.w3.org/Style/Examples/007/center.en.html, and thinking I could have just used left and margin-right styles set to 50% and -50% respectively to get the same effect. This just points out I have to keep in mind the default behavior of each element.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s