Mark Chapel
Mark Chapel

Reputation: 497

How to align-items: center AND align-self: stretch?

I have an element I'd like to be (cross-axis) centered but also 'grow' to a nominal size even with too-little content, BUT ALSO 'shrink' when the width of the page becomes smaller than 350px wide.

HTML

<div class="parent">
  <div class="child">
    Some content
  </div>
</div>

SCSS

.parent {
  display: flex;
  flex-direction: column;
  align-items: center;

  .child {
    max-width: 350px; 
    align-self: stretch;
  }
}

Adding align-self: stretch; to .child does the job of making it 350px wide, but it seems to negate the align-items: center; in .parent

Is there a way to do this in CSS that I'm missing? Please note that the element can't just be 350px wide all the time - it must also respond to horizontal page resizing as it does in the example fiddle.

Fiddle: https://jsfiddle.net/1uqpxn8L/1/

Upvotes: 7

Views: 5045

Answers (3)

Luu Dai Hai
Luu Dai Hai

Reputation: 149

UPDATED

I think you should use justify-content to h-align child to center.

Please note, when you apply display: flex property to parent, you should apply flex property to child.

.parent {
  background: yellow;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.parent .child {
  background: black;
  color: white;
  text-align: center;
  flex: 1 1 auto;
  width: 100%;
  max-width: 350px;
}
<div class="parent">
  <div class="child">
    I should be 350px wide
    <br> and centered in the yellow
    <br> unless the page gets smaller,
    <br> in which case I should have
    <br> 10px padding on either side.
  </div>
</div>

Please see the result here, hope this is what you mean: https://jsfiddle.net/1uqpxn8L/11/

Upvotes: 7

Sanira Liyanage
Sanira Liyanage

Reputation: 1237

You just need to remove the flex-direction property. Then it's working as you expected. But there will be a problem if you want to display children elements as column manner. The shrinking problem occurs with the flex-direction property or flex-flow:column values as I checked.

Upvotes: 0

Smokey Dawson
Smokey Dawson

Reputation: 9240

You can do something like this.

HTML

<div class="parent">
  <div class="child">
    Some content
  </div>
</div>

SCSS

.parent {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 10px;
  .child {
    width: 350px;
    @media(max-width: 350px) {
       width: 100%;
    }
  }
}

.parent {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 10px;
  background-color: red;
}

.child {
  width: 350px;
  background-color: yellow;
}

@media(max-width: 350px) {
  .child { width: 100%; }
}
<div class="parent">
  <div class="child">
    Some content
  </div>
</div>

So whats happening is I'm using a media query to change the width of the child depending on the width of the browser.

Upvotes: 1

Related Questions