PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 6, 2022

[FIXED] How to show middle of image in div using css?

 May 06, 2022     css, css-position, html, image, position     No comments   

Issue

How to show middle of image in div using css ?

https://jsfiddle.net/yn7hubkd/

CSS:

.out{
    width: 500px;
    height: 500px;
    overflow: hidden;
}

HTML:

<div class="out">
  <img src="https://redditupvoted.files.wordpress.com/2016/03/waffles-cat.jpg">
</div>

I get this output: http://i.imgur.com/gYzP1xo.png

But I want to get it like this (centered in x-direction, black square is image and red square is div class out): http://i.imgur.com/9QGVYtN.png

The output result is: http://i.imgur.com/EqzM7QO.png


Solution

This behaviour can simply be achieved by using the image as background. Just set background-size: cover; and background-position: center; to fill the container with the image and position it in the center:

.out {
  width: 500px;
  height: 500px;
  overflow: hidden;
  background-image: url(https://redditupvoted.files.wordpress.com/2016/03/waffles-cat.jpg);
  background-size: cover;
  background-position: center;
}
<div class="out"></div>

In case that you are forced to use the <img /> tag, simply add a negative left margin of 50%:

.out {
  width: 500px;
  height: 500px;
  overflow: hidden;
}
.out img {
  margin-left: -50%;
}
<div class="out">
  <img src="https://redditupvoted.files.wordpress.com/2016/03/waffles-cat.jpg">
</div>



Answered By - andreas
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing