I’m trying to make square images from rectangular in css. They also need to be centered.
I’ve read a lot of questions here, but the answers, good as they might be, always use constant sizes in pixels whereas I need tem to be in percents so the theme can remain responsive.
Basically I need to change this:
into this:
but if the screen is even smaller:
The main problem here is I cannot predict the screen size. It is designed for mobile, so they can vary.
I was thinking about doing css in php (it’s for wordpress so it’s possible). I was thinking something like width:50% and use the width as a variable, but if I set the height to be equal to width, it will be 50% as well. Is there a way to, I don’t know, convert the width to pixels or something? I’m out of ideas, please help.
The problem is, that it is just not possible to change the height relative to the width. So your problem is not the image itself (using overflow: hidden or background-size: cover will do that) but having the square size of your container with dynamic width and then the same height.
A very strange way would be to use a square image (_blank.png with 1px x 1px) and add width: 100% so the height will be the same.
with css:
div{width: 30%;}
img{width: 100%;}
and then add your actual picture as background-image with
background-size: cover;
background-position: center;
Neither performant nor beautiful, but it works.
have you tried this
make sure there is no height for img in your css file. Also make sure not to set something like height=”500px” width=”500px” in your html/php file.
also to be centered just do
Nice picture 😉
If you have an image you want centred—but covers—a parent element, using CSS only, then you’ll need two wrappers:
This works only for wide images. Portrait images will just centre themselves within the container.
Just use
img{max-width:100% !important; margin:0 auto !important;}
and I think it will help you.Try following css for your image. It won’t break the pixels/dimensions for the image.