1

I am trying to vertically center my background in a div. I made a schema for a better comprehension:

This is what i have for now :

enter image description here

The only problem as you can see, is that the image is taller than the div.

I don't want to resize the image, but just want to the image to be centered within the div.

I have made a second image to explain : enter image description here

I tried vertical-align:center but it didn't work either.

I can't post the jsfiddle because i havn't the reputation to post more than two link... I post it on the comment.

5
  • the jsfiddle : jsfiddle.net/gRtrX/29
    – Droïdeka
    Jun 15, 2014 at 13:32
  • try doing this (background-attachment : absolute;)
    – Shashank
    Jun 15, 2014 at 13:38
  • 2
    It's really not easy to understand what you are trying to do in that fiddle. Perhaps describe what you are aiming for in the fiddle in place of the Lorem ipsum.
    – ralph.m
    Jun 15, 2014 at 13:57
  • @ralph.m in the center of the image there is some colored figure. The image is not center, i just see the top of the image not the center like i want. EDIT : i have the answer :) jsfiddle.net/gRtrX/31
    – Droïdeka
    Jun 15, 2014 at 14:23
  • @ShashankSharma thx, this what i want ! Maybe you can post this a an answer, i can accept and close the post :)
    – Droïdeka
    Jun 15, 2014 at 14:26

2 Answers 2

1

Try doing this background-attachment : absolute;

OR

Simply remove this code background-attachment : fixed;

1
  • 1
    absolute is not a value for background-attachment. So adding this is the same as doing nothing, because the browser will ignore it.
    – ralph.m
    Jun 15, 2014 at 22:56
1

There is a css property named background-position. background-position takes a x and y value so if you set your background position in your case to 0% 50%. This will move the background position 0% to the right and 50% down (center).

background-position:0 50%;

jsfiddle example

While you are at it also take a look at background-size, background-size has some handy properties 'cover', 'contain'.

cover

Scale the background image to be as large as possible so that the background area is completely covered by the background image. Some parts of the background image may not be in view within the background positioning area.

contain

Scale the image to the largest size such that both its width and its height can fit inside the content area

Together with background-positition you can manage your background sizing and positioning according to the div pretty well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.