slevin
slevin

Reputation: 3886

Responsive image keeps aspect ratio and is always in the center

I want to use css to make an image keep its aspect ratio (16:9) and be responsive at the same time.

This image will always be in the center of the screen. Check the schema to help you.

I found this post and I tried Chris's solution and Isaac's solution. But I cannot bring the image to the center. I tried using Bootstrap like so.

<div class="col-md-4">.col-md-4</div>
<div class="wrapper col-md-4">
  <div class="main">
    This is your div with the specified aspect ratio.
  </div>
</div>
<div class="col-md-4">.col-md-4</div>

or

<body>
  <div class="col-md-4" id="wrap1">.col-md-4</div>        
    <div class="col-md-4" id="aspectRatio">Aspect Ratio?</div>
  <div class="col-md-4" id="wrap2">.col-md-4</div>        
</body>

but all the divs appear the one underneath the other.

Any ideas on how to bring the div in the center, by using Bootstrap or not?

Thanksenter image description here

Upvotes: 0

Views: 434

Answers (2)

Judder
Judder

Reputation: 1

This will center your element on the page.

.element {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
}

I believe you would have to define a min-width or max-width for your image at 100% of a container that is at the aspect ratio that you want for the second part of your question. Also, if you need to dynamically set the aspect ratio there is always JS. Qjuery has functions you can use I think so that will not hard if you are already using it inside of your project.

EDIT: to center the image in your second header I would suggest having a structure such as:

-second header

---------wrap

-----------------image

have the image as 100% size of the wrap. have the wrap relative to the second header with a width and height of 100% relative to it.

I hope this helps :)

Upvotes: 0

Ryuk
Ryuk

Reputation: 75

I always put my img in a div and center the div with:

margin:0 auto;

And for responsive image define width and make the height is auto. Hope it helps.

Upvotes: 1

Related Questions