Cannot center a fluid image in a fluid Div

79 views Asked by At

I'm having an issue with horizontally centering a fluid image in a fluid div. From looking high and low, the solutions others have found are not working for me, either I'm trying to do something too hard (I doubt it) or I'm working with different medium.

HTML:

<body>
  <div id="BackgroudDiv">
    <img src="images/NumberTwo.png" alt="" id="FSBG"/>
  </div>
</body>

CSS:

body {
    margin: 0px
}
#FSBG {
    width: auto;
    height: 100%;
    min-width: 1040px;
    position: absolute;
    min-height: 585px;
}
#BackgroudDiv {
    width: 100%;
    height: 1080px;
    text-align: center;
    display: block;
    background-color: #BF2527;
    top: 0px;
    left: 0px;
    right: 0px;
    bottom: 0px;
}

"Margin: auto" does nothing as the width of everything is variable. In the code as it is, the left edge of the image "NumberTwo" is centered on the page. I want the center of the image to be centered. It behaves just as it should scaling-wise, but not in the middle of the page!

Any help would be much appreciated, it's been driving me up the wall. Let me know if more information is needed.

H

3

There are 3 answers

3
lmgonzalves On BEST ANSWER

You only need to remove the position: absolute; in the img:

#FSBG {
    width: auto;
    height: 100%;
    min-width: 1040px;
    min-height: 585px;
}

DEMO: https://jsfiddle.net/3w5rqg3d/1/

1
Matt Hammond On

As you are using position absolute, you need to set the top, right and left to 0px; and then you can add margin-left and margin-right auto.

Example - https://jsfiddle.net/zvbn2fak/

top:0px;
left:0px;
right:0px;
margin-left:auto;
margin-right:auto; 

Please note that this is not best practice using position absolute on an image when its not need. Please read the comment by lmgonzalves, below with a better fix.

1
Achrome On

You can use flexbox, but be wary that flexbox is not supported on older browsers.

#backgroundDiv {
  display: flex;
  justify-content: center;
}

And that's it. justify-content aligns the items inside in the flexbox along the direction of the flex. I'm not sure if it works on position: absolute items, but you can check it out.

Note: I've left vendor prefixes for the sake of brevity, but you'll likely have to add those to get the desired effect across browsers.