简体   繁体   English

如何在不改变html和比率的情况下裁剪图像高度(并使其居中)?

[英]How to crop image height (and center it) without changing html and ratio?

In wordpress, I want to show a height reduced image but keeping width and ratio. 在wordpress中,我想显示高度缩小的图像,但保持宽度和比例。 The image is 400px large and 300px height. 图像大400px,高300px。 I want it 400px large but only 200px height, and centered. 我想要400px大,但只有200px的高度,并且居中。

This solution may help me but is uses div ? 这个解决方案可以帮助我,但是使用div? Crop and center image without using background-image But I can't add any div around image because wordpress doesnt create any. 不使用背景图像的裁剪和中心图像但是我无法在图像周围添加任何div,因为wordpress不会创建任何div。 May be could I create a div using PHP ou JS ? 也许我可以使用PHP ou JS创建一个div?

Here is the html created by Wordpres : 这是由Wordpres创建的html:

<p>
    <a href="http://finance.blog.lemonde.fr/files/2012/09/IMG-20120909-00051.jpg">
        <img width="400" height="300" src="http://finance.blog.lemonde.fr/files/2012/09/IMG-20120909-00051.jpg">
    </a>
</p>

and a JSFiddle to try : http://jsfiddle.net/v4w90e29/ 和一个JSFiddle尝试: http//jsfiddle.net/v4w90e29/

If anyone can help me, thanks a lot !!! 如果有人可以帮助我,非常感谢!!!

Use JQuery document ready function with this code 使用此代码使用JQuery文档就绪函数

var divs = jQuery("img");
for(var i = 0; i < divs.length; i+=3) {
divs.slice(i, i+3).wrapAll("<div class='wrapper'></div>");
}

After this your image will be in the div with class wrapper. 在此之后,您的图像将使用类包装器在div中。 After that just simple css. 在那之后只是简单的CSS。 For wrapper it will be: 对于包装器,它将是:

.wrapper {height:400px; width:200px; overflow:hidden;}

You can wrap the image very easily with jQuery. 您可以使用jQuery轻松地包装图像。

 $(document).ready(function() { // let's only include the images in paragraphs as the site most likely has other img elements somewhere. var paragraphImages = $("p img"); paragraphImages.each(function() { $t = $(this); // $(this) -> the current img in the loop. $t.wrapAll("<span class='wrapper'></span>"); // margin-top = negative of images height divided by 2. $t.css("margin-top", -$t.height()/2); }); }); 
 pa img { max-width: 400px; } .wrapper { height: 200px; width: 400px; overflow: hidden; display: block; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> <a href="http://finance.blog.lemonde.fr/files/2012/09/IMG-20120909-00051.jpg"> <img width="1000" height="750" src="http://finance.blog.lemonde.fr/files/2012/09/IMG-20120909-00051.jpg"> </a> </p> <p> <a href="http://finance.blog.lemonde.fr/files/2012/09/IMG-20120909-00051.jpg"> <img width="1000" height="400" src="http://finance.blog.lemonde.fr/files/2012/09/IMG-20120909-00051.jpg"> </a> </p> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM