[英]CSS: Relative position in absolute position in a relatively positioned 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步
找到一種方法來調整圖像大小以適合/填充其容器。 我建議以下解決方案。
后端:通過圖像處理庫(如GDlib或ImageMagick)裁剪圖像。 這樣,用戶將只需要下載所需的數據。
CSS:使用background-size:如果您不關心舊版瀏覽器支持並且無權訪問服務器端圖像操作,則進行覆蓋。
.UserImage {background-size:cover;
背景圖片:url( http://placekitten.com/200/400 ); }
3:JS:使用DOM操作定位和裁剪圖像容器。 這與使用服務器端圖像庫的數學基本相同,但缺點是將負載(帶寬和處理)放在客戶端上。
希望能對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.