Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center two elements side-by-side using flexbox

Tags:

html

css

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/

like image 744
John Avatar asked Jul 25 '16 18:07

John


1 Answers

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

like image 123
Michael Benjamin Avatar answered Sep 22 '22 07:09

Michael Benjamin