Ender Ady
Ender Ady

Reputation: 59

Using flexbox to keep a container centered and shrink on resize

I need the .aboutContent to stay the same size but the margins to left and right to shrink while decreasing screen size.

Similar example: the What’s on Spotify? div box on the Spotify website.

#about {
  width: 1920px;
  height: 500px;
  display: flex;
}

.aboutContent {
  width: 1250px;
  height: 100%;
  background-color: red;
  margin-left: 20%;
}
<div id="about">
  <div class="aboutContent"></div>
</div>

Upvotes: 1

Views: 820

Answers (2)

GuCier
GuCier

Reputation: 7425

I use to love your original title ("Flexbox margins or whatever"), but as James changed it, now I have to post two solutions. What a life.

Good ol' margins

Here is some CSS or whatever that centers content. With the help of margins & stuff.

Browser support : >= IE7. Should do it I guess.

div {
  background-color: orange;
  max-width: 500px;
  margin: 0 auto;
}
<div>HTML or whatever</div>

Shiny flexbox

Now the title is explicitely Flexbox, here is a new snippet. And for the same price you'll have a free Nicolas Cage picture.

Browser support : >= IE11. Should do it as well because people with browsers below IE11 are not used to see correctly layed out websites and we don't want to confuse them.

body {
  display: flex;
  justify-content: center;
}

img { /* Or div, or article, or whatever */
  flex : 0 1 500px;
}
<img src="https://www.placecage.com/500/230"/>

By the way, flex: 0 1 500px means :

  • 500px : By default, your size is 500px
  • 0 : Nope, you won't expand over your 500px basis
  • 1 : Yep you'll srink if your parent width is below 500px

It's not black magic f**kery, flex is awesome.

Upvotes: 5

motss
motss

Reputation: 668

Maybe set the max width to be certain percentage from its parent instead of a fixed value?

Upvotes: 0

Related Questions