0

I have a carousel and I need to display text at the center of the carousel (both horizontally and vertically center). so I went using the flex display property and I didn't get the expected results.

.heroText {
  display: flex;
  position: absolute;
  align-items: center; // align the element vertically center
  justify-content: center; // align the element horizontally center
  z-index: 999 !important; // display the text above carousel
}
<div class="heroText">
  <p>farmers</p>
</div>
Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
naveen
  • 560
  • 6
  • 15
  • Not sure if it's for the question, or if that's your actual CSS, but note that `//` is not the proper comment syntax. – Tyler Roper Oct 04 '19 at 16:24

3 Answers3

0

align-items and justify-content aren't aligning the element, but its' children.

If you want to center an absolutely positioned element to its relative parent, try adding this to .heroText:

top: 50%;
left: 50%;
transform: translate(-50%, -50%);

Alternatively, make the parent of .heroText display flex, and move the align and justify lines to that parent's class instead.

Afrophysics
  • 579
  • 3
  • 14
0

With flex you can just set the direction to column and justify the columns in the center. No need for strange translate, especially since you were already wanting to use flex.

.heroText {
  width: 50%;
  height: 10em;
  border: 1px solid black;
  
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
}
<div class="heroText">
  <p>farmers</p>
</div>
GammaGames
  • 1,617
  • 1
  • 17
  • 32
0

CSS align-content would center the content instead of the child elements, but regardless absolute positioning removes the element from the document flow. You can't use both.

Use this for centering instead.

.heroText {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Note: If your only reason for using position: absolute is to enable z-index. You could try position: relative instead which should allow flex-box to continue working as expected.

Bryce Howitson
  • 7,339
  • 18
  • 40