Skip to content

Instantly share code, notes, and snippets.

@anthonyringoet
Created October 9, 2012 07:12
Show Gist options
  • Save anthonyringoet/3857126 to your computer and use it in GitHub Desktop.
Save anthonyringoet/3857126 to your computer and use it in GitHub Desktop.
Center with calc(), tip from Lea Verou presentation
/**
* Center with calc(), tip from Lea Verou presentation
*/
body{
/* housekeeping */
background: #ffa;
min-height: 100%;
font-family:sans-serif;
}
section{
background:#0f0;
width:60%;
margin:0 calc(50% - 30%);
}
<!-- tip from http://lea.verou.me/more-css-secrets -->
<section>
<p>Centered inside</p>
</section>
{"view":"split","fontsize":"100","seethrough":"","prefixfree":"1","page":"all"}
@ngryman
Copy link

ngryman commented Mar 2, 2013

Great tip.

I also add margin: 0 auto as a fallback if calc is not supported. The background does not spread on the whole page, but at least the content is centered :)

@maxhoffmann
Copy link

I’ve just stumbled across this looking for Lea’s talk. calc() only makes sense when you have mixed value types like % and px. As you are only using percentages in your example you don’t need calc. Just do the math:

margin:0 calc(50% - 30%); => margin:0 20%;

@ineentho
Copy link

Here's Lea's slides: http://lea.verou.me/more-css-secrets/#padding-auto

This is what she really does:
section {
width: 700px;
padding: 0 calc(50% - 350px);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment