我们使用“图像的布局占位符”任务示例研究填充顶部属性的百分比工作原理

当我们进行采访时,经常有人问我们关于布局的问题。 通常,它们只是列出显示属性的值或如何使元素居中。 坦白地说,这让我感到困扰,我想提出自己的任务,借助这些任务,我可以测试布局技能,而不是他如何记住属性值。


任务说明


通常,当我在Internet上阅读文章时,会遇到以下问题:加载图像后,文本开始跳转。



该问题的一种解决方案是为图像添加一个占位符,其中宽度和高度的比率将重复图像的长宽比。



我将从标记开始实施:


<div class="post"> <img src="example.jpg" class="post__img" alt="   "> </div> 

要设置占位符的尺寸,您需要了解图像的长宽比。 例如,我将使用图像尺寸1920x1080px。


但是,如果您显示此尺寸的图像,则在大多数屏幕上将以水平滚动显示该图像。 因此,我将.post元素的最大宽度设置为640px,图像宽度将调整为该宽度。


 .post { max-width: 640px; } .post__img { max-width: 100%; } 

我将使用before伪元素在页面中添加一个占位符。 您还需要记住将图像放在其顶部。


 .post { max-width: 640px; position: relative; } .post::before { content: ""; } .post__img { max-width: 100%; position: absolute; top: 0; left: 0; } 

现在,您需要占位符的宽度来重复图像的宽度。 之前,我使图像占据了父.post元素宽度的100%。 在添加display:块之前,我将对伪元素执行相同的操作。


 .post { max-width: 640px; position: relative; } .post::before { content: ""; display: block; } .post__img { max-width: 100%; position: absolute; top: 0; left: 0; } 

朋友,就此,我完成了我的工作,而你的工作仍然存在。 您需要计算before伪元素的高度。


为此,请使用padding-top属性和百分比值。 若要正确执行此操作,您需要了解对padding-top属性进行计算的兴趣。 还要记住,图像尺寸为1920x1080px。


 .post { max-width: 640px; position: relative; } .post::before { content: ""; display: block; /*    padding-top    % */ } .post__img { max-width: 100%; position: absolute; top: 0; left: 0; } 

我希望您尝试自己解决此问题。 但是,如果出现困难,下面是我的解决方案。


解决方案


padding-top和padding-bottom属性具有一项非常有用的功能。 如果以百分比设置值,则将根据父块的宽度来计算它们。


因此,知道了这一点并记住了图像的大小(1920x1080px),您可以使用比例计算占位符的padding-top:


 padding-top = ( * 100%) /  = (1080 * 100% ) / 1920 = 56.25% 

其中ShiVi是图像的宽度和高度。


仍然需要为padding-top添加值:


 .post { max-width: 640px; position: relative; } .post::before { content: ""; display: block; padding-top: 56.25%; } .post__img { max-width: 100%; position: absolute; top: 0; left: 0; } 

Source: https://habr.com/ru/post/zh-CN433710/


All Articles