2

I have a flex container with some text (an h1, for example) that has a line break due to the width of the container. I'm trying to keep the text inline so that it doesn't automatically take up 100% of the width of the container, so that it stays centered horizontally, but having Flex on the container breaks this. I've tried using align-self: center on the h1 and a number of other things with no luck. Any help would be much appreciated.

Edit: I want to keep the text itself left-aligned, but have the h1 element centered within the container.

.container {
  width: 250px;
  background-color: tomato;
  
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

h1 { 
  display: inline; /* should only take as much space as it needs */
  align-self: center; 
}
<div class="container">
   <h1>Text text sdfsdlfkjs</h1>
</div>
Tim
  • 177
  • 8
  • 2
    Your h1 element is already taking up the entire width of its parent. That's why the part of inline text (sdfsdlfkjs) is returned onto a new line because it couldn't entirely fit within the width of its parent. That is why you cannot center h1 element within its parent, because it's already taking its parent's entire width. You can simply confirm this by putting the border around your h1 element. – Mers Apr 08 '18 at 05:55
  • 1
    Related...if not dupe - https://stackoverflow.com/questions/37406353/make-container-shrink-to-fit-child-elements-as-they-wrap – Paulie_D Apr 08 '18 at 09:10
  • ...or https://stackoverflow.com/questions/34995740/css-when-inline-block-elements-line-break-parent-wrapper-does-not-fit-new-width – Paulie_D Apr 08 '18 at 09:11
  • 1
    Align-self: center won’t work because the element is taking the 100% width of the container even when you see the white space. So the only way is to reduce the width of the h1. – Fernando Hernandez Apr 08 '18 at 18:49

1 Answers1

1

Is this what are you looking for?

.container {
 width: 250px;
 background-color:tomato;
 display: flex;
 flex-direction: column;
 justify-content: center;
}

h1 {
width: 90%;
margin-left: auto;
margin-right: auto;
border: 1px solid white;
}