Adrien
Adrien

Reputation: 57

How to center an image on the middle of the page in css?

How can I center something like this right on the middle of the page horizontally?

HTML -

 <div class="inner">
<img src="img/shoplove-design.png" alt="Recipe App" />
</div>

CSS
.inner {
width: 800px;          
 }

Upvotes: 1

Views: 13381

Answers (5)

Marie Brown
Marie Brown

Reputation: 1

I had this same question...Use this https://www.w3schools.com/css/css_align.asp

Or without table:

.center {
    padding: 200px 0;
    text-align: center;
    }

Upvotes: 0

Mr. Hugo
Mr. Hugo

Reputation: 12590

If you are OK with using a background image, you can also to this:

<html><head><style>
html, body {height: 100%}
body {
  background-image: url(img/shoplove-design.png); 
  background-position: center center; 
  background-repeat: no-repeat; 
  background-size: contain;
}
</style></head><body></body></html>

This gives the page 100% height and shows the image in the center. To get a better understanding of how the CSS works, I deliberately did not shorten the CSS statements.

A working example: http://codepen.io/anon/pen/bpjZjb?editors=1100

The good thing about this solution is that it is fully responsive and can easily be adjusted to your needs. Here is an example with the div element of the OP: http://codepen.io/anon/pen/BKPbqX?editors=1100

Upvotes: 0

Michael Schwartz
Michael Schwartz

Reputation: 8425

The easiest solution is to use text-align: center; see it in action.

This works because img is a child of div.inner. Thus div.inner being that it's a div element by default it's a display: block; Thus will have a width: 100%; of it's parent.


Now if you wanted to say align the image vertically as well div.inner would need to be display: table-cell; and it's parent would need to be display: table;.

Then vertically aligning the image is as simple as adding vertical-align: middle; to .inner.

Example Weave: http://kodeweave.sourceforge.net/editor/#fcad28261445fbcae79a9253f502cd2d

Upvotes: 0

Iakovos Exadaktylos
Iakovos Exadaktylos

Reputation: 141

Try attaching a class to your image like

<img class="centered" src="img/shoplove-design.png" alt="Recipe App" />

and define it like:

.centered{width:270px;  /* use yours*/
          height:150px; /* use yours*/
          position:absolute;
          left:50%;
          top:50%;
          margin:-75px 0 0 -135px;} /* use yours divided by 2*/

Upvotes: 0

atypical
atypical

Reputation: 1100

You should give a width to your img to align horizontally using margin-left:auto margin-right:auto.

 .inner {
   width: 800px;
   border:1px solid black;
 }

 img{
   display:block;
   margin:0 auto;
   width:200px;
 }

JSFiddle

Or you can align the img by making it inline-block and give a text-align:center to its parent

 .inner {
   width: 800px;
   border:1px solid black;
   text-align:center;
 }

 img{
   display:inline-block;
 }

JSFiddle

Upvotes: 2

Related Questions