John John - 4 months ago 6
HTML Question

Center two elements side-by-side using flexbox

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/

Answer

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 will create the flex container.
  • flex-direction: row, a default setting (i.e., it can be omitted), makes the main axis horizontal and aligns the children (flex items) along this axis
  • justify-content: center will center the flex items along the main axis

More details here: Methods for Aligning Flex Items

Comments