- 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.
- 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
- 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.
- 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, usetext-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;
.
- Thought 1: