Difficulty centering an image Solved thanks to an awesome community

/* cant seem to get the image to center on top of the two other elements. Any help would be most appreciated*/
I can achieve it by setting margin measurements at pixels the problem comes in when setting it to auto.

I want it to stay centered regardless of window size

code at:

Hi @ChrisCline1138,

Are you working on this code in codepen or something? If so, please share the link. It would be easier to debug the code. Thanks!

no I was just experimenting with one of the exercises here
thanks

Hi, Chris,

So, just use codepen.io to write your code and share the link here to us.
This is an easy way to help you!

1 Like

Well, there are a few things going on. First, an image is an inline element (rather than a block-level one). Things like divs, or tables, or articles – these are block-level. Their usual behavior is to display as a chunk, pushing the following bits around. Things like span tags, or anchors, are usually inline. As are images.

You CAN use an image as you have, simply by adding the CSS rule:

display: block

to it.

Also, it might help to put both the image and the two divs into a container of some sort, set THAT to absolute positioning, and set the image and two contained divs to relative.

Take a look at https://repl.it/@TobiasParent/centeringAnImage to see what I mean.

will try that
thank you

must say the amount of support is awesome

We’ve all been there. Some of this stuff can be confusing, and it helps to have a support system. Back in my day… lol

I have not started the css flexbox lessons I’m thinking this gets covered there but I got curious about it so I figured I’d give it a try.

And using positioning, you can SIMULATE flexbox effects. But it is WAY more work. :wink:

that is what I am gathering.

thanks
created my first pen

…and the link to your pen? Show us the code! :smiley:

You can try this.

<div class="container">
  <img src="https://indiehoy.com/wp-content/uploads/2018/05/evaristo-paramos.jpg" alt="EVARISTO PARAMOS">
  <div class="one"></div>
  <div class="two"></div>
</div>


.container {
  position: relative;
  width: 100%;
  height: 300px;
  border: 1px solid red;
  display: flex;
  justify-content: center;
  align-items: center;
}

.one {
  width: 50%;
  height: 300px;
  background: repeating-linear-gradient( 45deg, yellow 0px, yellow 40px, black 40px, black 80px );
  position: absolute;
  top: 0;
  left: 0;
}

.two {
  width: 50%;
  height: 300px;
  background: repeating-linear-gradient( -45deg, yellow 0px, yellow 40px, black 40px, black 80px );
  position: absolute;
  top: 0;
  right: 0;
}

You could also use this code:

img {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

  z-index: 2;
  width: 30%;
  height: auto;
}

This will center the image in the middle of the screen.

Thank you so much
that is exactly what I was going for

Link to solution

2 Likes

thanks for your support