Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save martensonbj/99d398d58da12da24329592b5394f010 to your computer and use it in GitHub Desktop.
Save martensonbj/99d398d58da12da24329592b5394f010 to your computer and use it in GitHub Desktop.
Make Divs Follow the Rules

HOW DO I MAKE THIS DIV LISTEN TO ME

Background

  • One of the more frustrating aspect of styling a web page is putting HTML elements in the center of the page and making divs line up the way you want. There are multiple ways to do this and in my talk I want to go over why you'd use one vs another.

Concept 1: float & clearfix

  • Using Float to move elements to the left or right
  • Why it's important to use clear: both after using float
  • Setting up a "clearfix" hack

Concept 2: display: inline vs display: block vs dispaly: inline-block

  • Display: Inline --> Elements flow side by side and don't listen to any style changes for height or vertical spacing. All behaviors are horizontal and do not create any line breaks
  • Display: Block --> Elements are separated by a line break and flow from top to bottom. Examples include divs, H1-H6, paragraphs...etc.
  • Display: Inline-Block --> Elements flow side by side but also listen to height and margin specifications. Best of both worlds if you need flow control horizontally.

Option 3: margin: 0 auto

  • Regardless of how you want your elements to flow, these are important things to try to when centering an element.
    • Thought 1: text-align: center does more than center text. Think about what is wrapped around the element you are trying to center. For example, if you want to center the text within a div, use text-align: center(seems obvious), but this treats ALL elements within that div like text (including text).
    • Which bring us to Thought 2: If you want to center a div within a div, ALSO use text-align: center on the parent element.
    • Thought 3: F dealing with the text, I just want this div to be in the center of its parent element. Webpages don't know how to handle elements that don't have a specified width. HOw do I center something if I don't know how much space it takes up? Fix this by specifying a width on the element you want to center, and then set set margin: 0 auto;.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment