9

How to use CSS flex to horizontally center an anchor and a paragraph next to each other on a page?

I'm trying to avoid using float on the anchor and paragraph though I've not exactly mastered flex.

The anchor/image should appear to the left of the paragraph though they as a whole should remain centered.

What I've got to thus far:

section
{
 align-items: center;
 display: flex;
 flex-direction: column;
}
<section>
 <a href="#">
  <img alt="Example" src="https://jsfiddle.net/img/logo.png" />
 </a>
 <p>Description goes here...</p>
</section>

https://jsfiddle.net/eondkrpd/

John
  • 1
  • 13
  • 98
  • 177

1 Answers1

19

section {
  display: flex;
  justify-content: center;
}
<section>
  <a href="#">
    <img alt="Example" src="https://jsfiddle.net/img/logo.png" />
  </a>
  <p>Description goes here...</p>
</section>
  • display: flex creates the flex container
  • flex-direction: row, a default setting (i.e., it can be omitted), makes the main axis horizontal, aligning the children (flex items) in this direction
  • justify-content: center will center the flex items along the main axis

More details here: Methods for Aligning Flex Items

Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701