Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple center a object with css and no hacks

Tags:

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%; } 
like image 925
Caspert Avatar asked Feb 14 '13 20:02

Caspert


People also ask

How do I center anything with CSS?

To just center the text inside an element, use text-align: center; This text is centered.

How do I center align an object?

Select Picture format > Align and select how you want to align them: Align Left, Align Center, or Align Right. Align Top, Align Middle, or Align Bottom. Distribute Horizontally or Distribute Vertically.

How do I force an image to center in CSS?

To center an image ("[/]" denotes a line break): img. center { [/] display: block; [/] margin-left: auto; [/] margin-right: auto; [/] }.


2 Answers

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.

like image 161
CharlieM Avatar answered Nov 13 '22 13:11

CharlieM


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.

like image 39
daGUY Avatar answered Nov 13 '22 12:11

daGUY