Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS flexbox centering with a fixed width

Tags:

html

css

I'm trying to center a wrapper using flex box and fixed width. When I add a fixed width to the body like 100% and use margin: 0 auto; everything is thrown off center. I would like the wrapper to have a fixed width of 1000px and centered within the body (this is why I'm setting the body to 100%).

Any help is appreciated. HTML and CSS below.

HTML:

<!doctype html>
<html lang="eng">
<head>
    <meta charset="utf-8" />
    <title>Flex box layout</title>

    <link rel="stylesheet" href="webtemp.css" />
</head>

<body>

  <div class="wrapper">
  <header class="header">Header</header>
  <article class="main">
    <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>  
  </article>
  <aside class="aside aside-1">Aside 1</aside>
  <aside class="aside aside-2">Aside 2</aside>
  <footer class="footer">Footer</footer>
</div>
</body>


</html>

CSS:

.wrapper {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-flex-flow: row wrap;
  flex-flow: row wrap;
  font-weight: bold;
  text-align: center;
}

.wrapper > * {
  padding: 10px;
  flex: 1 100%;
}

.header {
  background: tomato;
}

.footer {
  background: lightgreen;
}

.main {
  text-align: left;
  background: deepskyblue;
}

.aside-1 {
  background: gold;
}

.aside-2 {
  background: hotpink;
}

@media all and (min-width: 600px) {
  .aside {
    flex: 1 auto;
  }
}
@media all and (min-width: 800px) {
  .main {
    flex: 3 0px;
  }

  .aside-1 {
    order: 1;
  }

  .main {
    order: 2;
  }

  .aside-2 {
    order: 3;
  }

  .footer {
    order: 4;
  }
}
body {
  padding: 2em;
}
like image 822
DBS Avatar asked Oct 18 '25 13:10

DBS


1 Answers

Apply fixed width and use margin:0px auto; to align center.

.wrapper {
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-flex-flow: row wrap;
flex-flow: row wrap;
font-weight: bold;
text-align: center;
width:300px;
margin:0px auto;
}

DEMO

like image 119
Suresh Ponnukalai Avatar answered Oct 21 '25 04:10

Suresh Ponnukalai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!