关于html:在内部div中设置max-height不起作用

Set max-height in inner div does not work

本问题已经有最佳答案,请猛点这里访问。

我有一个完全居中的div(itemSoldOutView)。 在此div内,还有另一个div(itemSoldOutViewContent),其最大高度应为父div的90%。 这样,如果内容过多,它就会滚动(注意:仅内部CONTENT-div应该滚动)。
但这是行不通的。 如何设置正确的高度?

这是我的代码(JSFIDDLE):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#shadow {
    position:fixed;
    left:0;
    top:0;
    width:100%;
    height:100%;
    background: darkgray;
    z-index:2;
}

#itemSoldOutView {
    background: white;
    position: absolute;
    padding: 15px;
    max-height: 80%;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

#itemSoldOutViewContent {
    overflow: auto;
  max-height: 90%;
}

#itemSoldOutViewCancel {
    position: fixed;
    right: 5px;
    top: 5px;
    width: 16px;
    height: 16px;
    background: red;
}
1
2
3
4
            This is the title text:
       
       
            // much content


如果要使用可滚动的div,只需将overflow:scroll放在CSS内。
这里的错误是将溢出属性放入#itemSoldOutView

还从父元素继承高度。

看到这个小提琴


您需要在容器div中用height替换max-height,并添加overflow: hidden

1
2
3
4
5
6
7
8
9
10
#itemSoldOutView {
    background: white;
    position: absolute;
    padding: 15px;
    overflow: hidden;
    height: 80%;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

然后在div中要滚动添加overflow-y: scroll

工作小提琴

另一个编辑:

实际上,您应该将内部div缩小一些,以显示所有可滚动项,这里我将max-height减小到80%:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#shadow {
    position:fixed;
    left:0;
    top:0;
    width:100%;
    height:100%;
    background: darkgray;
    z-index:2;
}

#itemSoldOutView {
    background: white;
    position: absolute;
    padding: 15px;
    overflow: hidden;
    height: 80%;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

#itemSoldOutViewContent {
    overflow-y: scroll;
    max-height: 80%;
}

#itemSoldOutViewCancel {
    position: fixed;
    right: 5px;
    top: 5px;
    width: 16px;
    height: 16px;
    background: red;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
            This is the title text:
       
       
            bla
            blabla
            bla
            blabla
            bla
            blabla
            bla
            blabla
            bla
            blabla
            bla
            blabla
            bla
            blabla
            bla
            blabla
            bla
            blabla
            bla
            blabla
            bla
            blabla
            bla
            blabla
            bla
            blabla
            last blabla


在CSS中,您可以使用

1
2
3
4
5
6
#itemSoldOutView{
   box-sizing: border-box;
}
#itemSoldOutViewTitle h3{
   position: fixed;
}

但是,当您的内容超出了div的容量时,内容将不断溢出。 如果您想摆脱它,请使用

1
2
3
4
5
6
7
#itemSoldOutView{
   box-sizing: border-box;
   overflow: scroll;
}
#itemSoldOutViewTitle h3{
   position: fixed;
}