繁体   English   中英

使用CSS制作相对定位的div正方形

[英]Make a relatively positioned div square with CSS

我想知道是否存在仅CSS解决方案,以确保相对定位的div在任何情况下都完全是正方形; 我有一个脚本,该脚本将允许用户上传图像,并将其应用于背景图像属性。

问题在于系统需要支持所有尺寸的图像,因此我不能仅设置特定的高度和宽度。

第1步

只需将div填充底部设置为100%即可创建固有比率,这意味着div不论宽度如何都将始终为正方形。 然后使用position:relative / absolute放置拉伸整个容器的子元素。

这是一种通用的CSS唯一技术,可以以特定的宽高比嵌入视频,但不限于特定的内容类型。

我创建了一个小提琴以查看其实际效果。 请注意:我在这里使用了SuitCSS的flex embed组件,但是您绝不会使用它。

http://jsfiddle.net/mlnmln/tfm6q/1/

HTML:

<div class="FlexEmbed FlexEmbed-ratio">
  <div class="UserImage FlexEmbed-content"></div>
</div>

CSS:

/*
 * FlexEmbed component from suit-css. 
 * @see: https://github.com/suitcss/components-flex-embed/blob/master/lib/flex-embed.css
 * @see: http://suitcss.github.io/components-flex-embed/test/
 * @see: http://alistapart.com/article/creating-intrinsic-ratios-for-video
 */ 

.FlexEmbed {
  display: block;
  overflow: hidden;
  position: relative;
}

/**
 * The aspect-ratio hack is applied to an empty element because it allows
 * the component to respect `max-height`. Default aspect ratio is 1:1.
 */

.FlexEmbed-ratio {
  display: block;
  padding-bottom: 100%;
  width: 100%;
}

/**
 * Fit the content to the aspect ratio
 */

.FlexEmbed-content {
  bottom: 0;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0;
  width: 100%;
}

第2步

找到一种方法来调整图像大小以适合/填充其容器。 我建议以下解决方案。

  1. 后端:通过图像处理库(如GDlib或ImageMagick)裁剪图像。 这样,用户将只需要下载所需的数据。

  2. CSS:使用background-size:如果您不关心旧版浏览器支持并且无权访问服务器端图像操作,则进行覆盖。

    .UserImage {background-size:cover;
    背景图片:url( http://placekitten.com/200/400 ); }

3:JS:使用DOM操作定位和裁剪图像容器。 这与使用服务器端图像库的数学基本相同,但缺点是将负载(带宽和处理)放在客户端上。

希望能对您有所帮助。

暂无
暂无

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

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