search

Home  >  Q&A  >  body text

css3 - 自适应高度问题

如何在父级p高度是auto的情况下,子级p为父级p的一半,子级p里面有个图片高度为60(图片自己的高度,并没有给图片高度)。有没有实现的可能

大家讲道理大家讲道理2783 days ago568

reply all(8)I'll reply

  • 迷茫

    迷茫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

    1. If your image has a certain height, then setting a certain padding-top to #p2 is the easiest way

    2. If the height of the image is not certain, use JS.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦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

    reply
    0
  • 阿神

    阿神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

    reply
    0
  • 黄舟

    黄舟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)

    reply
    0
  • 阿神

    阿神2017-04-17 11:58:26

    Impossible, the child can be resized according to the parent only if it is not auto

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 11:58:26

    Isn’t this a chicken-and-egg problem?

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 11:58:26

    If there is no height, sub-p is the height of the picture

    reply
    0
  • 大家讲道理

    大家讲道理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

    reply
    0
  • Cancelreply