rallybilen
rallybilen

Reputation: 3257

Can't put margin on image

I am doing a website in wordpress. And under the navigation I have container(id="cover_photo") for image(id="cover_photo_image).I center it with margin but I want to move it down, and center it in the container, but the container follow if I put margin on it.

HTML

    <div id="cover_photo">
        <p id="cover_photo_image">
        </p>
    </div>

CSS

#cover_photo {
    width: 100%;
    height: 278px;
    background-color: #6b0c0b;
    box-shadow: inset 0px 0px 3px 0px #888, 0px 0px -3px 0px #888;
}

p#cover_photo_image {
    width: 821px;
    height: 172px;
    display: block;
    margin: 0 auto;
    margin-top: 6px;
    background-image: url(images/cover_photo.png);
}

Upvotes: 0

Views: 2729

Answers (2)

JackLiu
JackLiu

Reputation: 1

About vertical and horizontal centering.

You can use Flex.

Please add the following code

#cover_photo {
   display: flex;
   justify-content: center;
   align-items:center;
}

p#cover_photo_image {
  border: 1px solid black;
  background-repeat: no-repeat;
  background-image: url(https://cdn.sstatic.net/Img/teams/teams-illo-free- 
  sidebar-promo.svg?v=47faa659a05e);
  background-size: contain;
  background-position: center;
}

This should be the effect you want. enter image description here

Upvotes: 0

Michelle
Michelle

Reputation: 2712

Plopped your code into a fiddle and saw what you mean. The problem is that you haven't set positioning for #cover_photo or #cover_photo_image. The outer element needs to be relative, the inner needs to be an absolute.

#cover_photo {
position: relative;
}

p#cover_photo_image {
position: absolute;
}​

I changed the sizes so it would fit into the preview, and if you try adjusting the margin values it should move around and not move the #cover_photo container.

http://jsfiddle.net/ESCNm/

Just in case you're are looking to automatically vertically and horizontally align an element within an element, there are a LOT more methods that manual positioning. Manual positioning is such a hassle, and I try to avoid absolutes whenever possible.

Here an article about it: http://www.vanseodesign.com/css/vertical-centering/

Upvotes: 1

Related Questions