Cómo "recortar" una imagen rectangular en un cuadrado con CSS?


Sé que es imposible modificar una imagen con CSS, por lo que pongo crop entre comillas.

Lo que me gustaría hacer es tomar imágenes rectangulares y usar CSS para que aparezcan cuadradas sin distorsionar la imagen en absoluto.

Básicamente me gustaría convertir esto:

introduzca la descripción de la imagen aquí

En esto:

introduzca la descripción de la imagen aquí

Author: MD XF, 2013-03-02

8 answers

Asumiendo que no tienen que estar en etiquetas IMG...

HTML:

<div class="thumb1">
</div>

CSS:

.thumb1 { 
  background: url(blah.jpg) 50% 50% no-repeat; /* 50% 50% centers image in div */
  width: 250px;
  height: 250px;
}

.thumb1:hover { YOUR HOVER STYLES HERE }

EDITAR: Si el div necesita enlazar en algún lugar, simplemente ajuste HTML y Estilos de esta manera:

HTML:

<div class="thumb1">
<a href="#">Link</a>
</div>

CSS:

.thumb1 { 
  background: url(blah.jpg) 50% 50% no-repeat; /* 50% 50% centers image in div */
  width: 250px;
  height: 250px;
}

.thumb1 a {
  display: block;
  width: 250px;
  height: 250px;
}

.thumb1 a:hover { YOUR HOVER STYLES HERE }

Tenga en cuenta que esto también se puede modificar para que responda, por ejemplo, % anchos y alturas, etc.

 62
Author: Michael,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-26 15:28:15

Una solución CSS pura sin envoltura div u otro código inútil:

img {
  object-fit: cover;
  width:230px;
  height:230px;
}
 245
Author: Vision Hive,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-12 22:19:40
  1. Coloque su imagen en un div.
  2. Dale a tu div dimensiones cuadradas explícitas.
  3. Establezca la propiedad CSS overflow en el div en hidden (overflow:hidden).
  4. Pon tu imagen dentro del div.
  5. Beneficio.

Por ejemplo:

<div style="width:200px;height:200px;overflow:hidden">
    <img src="foo.png" />
</div>
 49
Author: j08691,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-01 22:02:19

Usando background-size: cover - http://codepen.io/anon/pen/RNyKzB

CSS:

.image-container {
  background-image: url('http://i.stack.imgur.com/GA6bB.png');
  background-size:cover;
  background-repeat:no-repeat;
  width:250px;
  height:250px;
}  

Marcado:

<div class="image-container"></div>
 29
Author: Philip Nuzhnyy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-23 11:48:30

En realidad me encontré con este mismo problema recientemente y terminé con un enfoque ligeramente diferente (no pude usar imágenes de fondo). Sin embargo, requiere un poco de jQuery para determinar la orientación de las imágenes (estoy seguro de que podría usar JS simple en su lugar).

Escribí una entrada de blog al respecto si estás interesado en más explicaciones, pero el código es bastante simple:

HTML:

<ul class="cropped-images">
  <li><img src="http://fredparke.com/sites/default/files/cat-portrait.jpg" /></li>
  <li><img src="http://fredparke.com/sites/default/files/cat-landscape.jpg" /></li>
</ul>

CSS:

li {
  width: 150px; // Or whatever you want.
  height: 150px; // Or whatever you want.
  overflow: hidden;
  margin: 10px;
  display: inline-block;
  vertical-align: top;
}
li img {
  max-width: 100%;
  height: auto;
  width: auto;
}
li img.landscape {
  max-width: none;
  max-height: 100%;
}

JQuery:

$( document ).ready(function() {

    $('.cropped-images img').each(function() {
      if ($(this).width() > $(this).height()) {
        $(this).addClass('landscape');        
      }
    });

});
 12
Author: FreddyBushBoy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-25 19:50:40

Use CSS: overflow:

.thumb {
   width:230px;
   height:230px;
   overflow:hidden
}
 1
Author: Diodeus - James MacFarlane,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-01 22:12:03

Tuve un problema similar y no pude "comprometer" con las imágenes de fondo. Se me ocurrió esto.

<div class="container">
    <img src="http://lorempixel.com/800x600/nature">
</div>

.container {
    position: relative;
    width: 25%; /* whatever width you want. I was implementing this in a 4 tile grid pattern. I used javascript to set height equal to width */
    border: 2px solid #fff; /* just to separate the images */
    overflow: hidden; /* "crop" the image */
    background: #000; /* incase the image is wider than tall/taller than wide */
}

.container img {
    position: absolute;
    display: block;
    height: 100%; /* all images at least fill the height */
    top: 50%; /* top, left, transform trick to vertically and horizontally center image */
    left: 50%;
    transform: translate3d(-50%,-50%,0);
}

//assuming you're using jQuery
var h = $('.container').outerWidth();
$('.container').css({height: h + 'px'});

Espero que esto ayude!

Ejemplo: https://jsfiddle.net/cfbuwxmr/1 /

 1
Author: Zach Botterman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-06 21:21:43

O bien utilizar un div con dimensiones cuadradas con la imagen en el interior con el .clase testimg:

.test {
width: 307px;
height: 307px;
overflow:hidden
}

.testimg {
    margin-left: -76px

}

O un div cuadrado con un fondo de la imagen.

.test2 {
width: 307px;
height: 307px;
    background: url(http://i.stack.imgur.com/GA6bB.png) 50% 50%
}

He Aquí algunos ejemplos: http://jsfiddle.net/QqCLC/1/

ACTUALIZADO PARA QUE LA IMAGEN SE CENTRE

.test {
  width: 307px;
  height: 307px;
  overflow: hidden
}

.testimg {
  margin-left: -76px
}

.test2 {
  width: 307px;
  height: 307px;
  background: url(http://i.stack.imgur.com/GA6bB.png) 50% 50%
}
<div class="test"><img src="http://i.stack.imgur.com/GA6bB.png" width="460" height="307" class="testimg" /></div>

<div class="test2"></div>
 1
Author: tech292,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-14 12:01:24