24

I want to center an object using CSS and no hacks, is this possible and how?

I have tried this, but than my p tag is gone.

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
}
svarog
  • 8,471
  • 4
  • 55
  • 66
Caspert
  • 3,977
  • 13
  • 44
  • 88

7 Answers7

39

There's several ways to center an element. But it depends on what your element is and how we choose to display it:

  • If you have {display:inline; }

    This is simple. You can just use "text-align: center;" to center text, images and divs.

  • If you have {display:block;}

    This is a bit more difficult. It depends on how your object is positioned. Your object could be relative, absolute, or fixed.

    • If it is relative; then you can use "margin:0 auto;", however you will require a width value.

    • If it is absolutely positioned, then you need to specify your "top:" and "left:" values. You'll also need a width. If you know the width of the element, the best way is to use {left:50%; margin-left:-X}, where X = 1/2 the width of the element.

Luiggi Mendoza
  • 81,685
  • 14
  • 140
  • 306
CharlieM
  • 658
  • 6
  • 9
6

HTML:

<div>Centered</div>

CSS:

div {
    margin: 0 auto;
    width: 200px;
}

Live example: http://jsfiddle.net/v3WL5/

Note that margin: 0 auto; will only have an effect if the div has a width.

daGUY
  • 22,638
  • 27
  • 70
  • 113
1

Use margin: auto like this:

margin: 0px auto
Mikhail Vladimirov
  • 12,571
  • 1
  • 31
  • 34
1

Use this for general purposes. Even span or div which is inside whatever :

width:inherit; display:block;margin:0 auto;
0

Usage :

  1. In-Line usage : Content goes here....
  2. CSS Code :

    #text-align { text-align:center }

HTML Code :

<div id="text-align">Content goes here....</div>

http://www.techulator.com/resources/4299-center-Deprecated-tags-HTML.aspx

Rajan471
  • 318
  • 4
  • 15
0

late into the game, but have you tried with display:flex on the parent ?

I have a useful class that is simple and works with all type of elements:

/* apply this on the parent */
.center {
    display:flex;
    align-items: center; /*vertical alignement*/
    justify-content: center; /* horizontal alignement*/
}

This is relatively new but supported at ~98% of major browsers.

However I suggest that you learn a bit about flexBox, it may seem complicated at first but it is very powerful for all type layouts !

GLAND_PROPRE
  • 3,318
  • 2
  • 21
  • 47
-4

if you don't need to be position:fixed; you can just use

<center>
Hello
</center>

This is deprecated in HTML5

Community
  • 1
  • 1
dan
  • 125
  • 1
  • 2
  • 9