-3

Centering an element only when screen is at max width

At the moment, I am centering various elements (by JavaScript) by calculating the screen's width and setting the element's "margin-left" to screen.width/2 - element.width/2.

I do this so that when the user resizes the window, the element will stay in the absolute center of the screen and become invisible if the window is resized to less than 50%.

Is this a typical way to center things only at the max width, or is there a simpler CSS approach to achieving the same effect?

An example of the effect I am trying to achieve: Khanacademy.com's logo.

[Edit] Thanks to hungerstar, I was able to figure out the root cause of my issue. If you do not set a min-width, then margin: 0 auto will always keep your element centered.

SeveN
  • 79
  • 5

3 Answers3

2

For block elements, giving an explicit width plus margin: 0 auto is the basic technique. Inline (and inline-block) elements such as images you can center using text-align:center on the parent container.

omma2289
  • 54,161
  • 8
  • 64
  • 68
1

You can achieve this using css.

margin: 0 auto;

EXAMPLE

Khawer Zeshan
  • 9,470
  • 6
  • 40
  • 63
  • This isn't working for me. When I resize the window, the element remains centered, which is not what I want. – SeveN Jul 22 '13 at 22:36
1

If you have a group of elements that need to be centered but need to maintain left alignment or other formatting, i.e. a heading followed by paragraphs with lists, you can do the following:

HTML

<div id="wrapper">
     <div class="outer">
         <div class="inner">... Content...</div>
     </div>
</div>

CSS

#wrapper {
     margin: 0 auto;
     width: 900px;
}
.outer {
     height: 50px;
     left: 50%;
     position: relative;
     display: inline-block; /* or float: left; */
}
.inner {
     right: 50%;
     position: relative;
}
hungerstar
  • 21,206
  • 6
  • 50
  • 59
  • This solution is not working for me either. When I resize my window, the element remains centered, which is not the desired result. – SeveN Jul 22 '13 at 22:41
  • Do you have a max width for the site? If so then use CSS3 media queries. You question is a little vague on the desired result. I would re-state what your objective is. – hungerstar Jul 22 '13 at 22:50
  • I am trying to center a logo ONLY when the browser is at maximum width. So basically, I want the window to be a frame and I do not want the logo to "re-center" itself upon resizing the window. – SeveN Jul 22 '13 at 22:55
  • See updated answer. That Kahn Academy logo is using a modified version of what I've posted. – hungerstar Jul 22 '13 at 22:57
  • I thought I already had my max width set. That was my issue. Thank you! – SeveN Jul 22 '13 at 23:03
  • For reference, if others end up on this post, it is better to use a min-width than a fixed width. – SeveN Jul 22 '13 at 23:10