使用CSS(也许JavaScript)使元素成方形(或保持特定的长宽比) [英] Use CSS (and maybe JavaScript) to make an element be square (or maintain a specific aspect ratio)

查看:109
本文介绍了使用CSS(也许JavaScript)使元素成方形(或保持特定的长宽比)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div,我想要有以下特征:

I have a div that I want to have the following characteristics:


  • 宽度=其父元素的50%

我需要使用百分比,因为当浏览器调整大小时,对象将左右调整。我想要对象的上下尺寸,以确保对象保持相同的长宽比。

I need to use percentages because the object will resize left-right when the browser is resized. I want the object to be resized top-bottom to ensure the object maintains the same aspect ratio.

我不认为有任何方式使用纯CSS做这个,但是有没有人知道一种方法?或者,是否有一个简单的JavaScript方法来做到这一点? (JQuery很好。)

I don't think there's any way to use pure CSS to do this, but does anyone know of a way? Alternatively, is there an easy JavaScript way to do this? (JQuery is fine.)

推荐答案

我想出了如何做到这一点没有js,虽然你需要使用透明的图像。

I figured out how to do this without js, though you need to use a transparent image.

设置一个html结构,例如:

Set up a html structure like:

<div class="rect_container"><img class="rect_image" src="rect_image.png"/>
 <div class="rect">Your favorite content here</div>
</div>

使用AxB透明png用于rect_image,其中AxB是长宽比。

Use a AxB transparent png for rect_image where AxB is the aspect ratio.

同时设置一个样式表,如:

Meanwhile set up a stylesheet like:

.rect_container {width: 50%; position: relative;}
.rect_image {width: 100%; display: block;}
.rect {width: 100%; height: 100%; position: absolute; left: 0px; top: 0px;}

这里重要的是利用图像保持其长宽比当在一个方向调整大小。同时,我们需要一个可用的div,所以我们使图像显示为块,将其包装在一个div中,并在其中放置一个绝对定位的div。我把这个代码从一个更复杂的东西我实际测试。奇迹般有效。

The important thing here is taking advantage of the fact that images maintain their aspect ratio when resized in one direction. Meanwhile, we need a useable div, so we make the image display as block, wrap it in a div, and put an absolutely positioned div inside that. I distilled this code from something more complicated I actually tested. Works like a charm.

这篇关于使用CSS(也许JavaScript)使元素成方形(或保持特定的长宽比)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆