如何在父级p高度是auto的情况下,子级p为父级p的一半,子级p里面有个图片高度为60(图片自己的高度,并没有给图片高度)。有没有实现的可能
迷茫2017-04-17 11:58:26
It’s really unclear. I want to change the question but I’m afraid it’s not what the questioner wanted to ask. Try to answer it.
First of all, you need to know that keywords such as auto, 50%, and em or relative unit lengths must be calculated to exact values (such as px).
If the height of the parent element is auto, then it is calculated based on the height of the child element.
According to the title description, the easiest thing to think of is:
<p id="p1" style="height:auto">
<p id="p2" style="height:50%"></p>
</p>
You can try it, but it doesn’t work. Why? The height of #p1 is calculated based on the height of #p2. And the height of #p2 is half of #p1. This creates interdependence.
The relative units in CSS are all calculated based on the parent element, except em, but they are not used here.
Solution
If your image has a certain height, then setting a certain padding-top to #p2 is the easiest way
If the height of the image is not certain, use JS.
伊谢尔伦2017-04-17 11:58:26
The description of the problem is a little confusing. Can you edit the question and explain it clearly again? And whether to use JS or only CSS
阿神2017-04-17 11:58:26
In terms of CSS, the height auto is supported by the content. Neither the parent nor the child element has a height set, so the actual height is only the image
黄舟2017-04-17 11:58:26
It always feels weird!
To achieve this, get the height h of the child p through js, and then set the height of the parent p to h*2
(Parent auto, there is only one picture in the child p, the height of the child p is also the height of the picture, directly set the parent height to 120)
阿神2017-04-17 11:58:26
Impossible, the child can be resized according to the parent only if it is not auto
大家讲道理2017-04-17 11:58:26
You can first get the height of the image through js, and then set the height of the child p and parent p