关于html:div的max-width不采用最大宽度

div with max-width not taking the max width

我有一个页面,该页面的div集中在" main " div中。主div是全宽度,而内部div的最大宽度等于" main " div的宽度。当用元素填充它时,它只能填充约一半的屏幕。我在做什么错?

编辑:
我注意到有些人误解了上面的文字。我的元素(带有float:左)将在其中4个元素之后彼此移动。那时div的宽度约为1000px。这意味着最大宽度不是100%,而是50%。我在浏览器和CSS中进行了检查,但是没有其他选择器可以覆盖这些值。

CSS :(无礼)

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
#main
  z-index: 0
  width: 100%
  min-height: calc( 100% )
  background: #FFFFFF
  position: absolute
  left: 0px
  top: 0px
  padding: 50px 0px
  text-align: center
  div.container
    position: absolute
    top: 50%
    left: 50%
    transform: translate(-50%, -50%)
    display: block
    max-height: 100%
    margin: 0 auto
    width: auto
    max-width: 100%
    overflow-y: auto
    overflow-x: hidden
    text-align: left

div.box
  width: 220px
  height: 200px
  border: 1px solid #5774FF
  padding: 19px
  margin: 10px
  float: left
  box-shadow: 1px 1px 4px #CCC

HTML:

1
2
3
4
5
6
7
            <form action="/save" method="post">
                <input type="text" placeholder="code" name="name"/>
                <select name="education">
                    <option value="3">option 3</option>
                </select>
                <button type="submit">save</button>
            </form>

您基本上是在告诉浏览器,容器div的最大宽度可以是其父容器的100%。这会使容器div变得流畅,因此它将对不同的屏幕尺寸做出响应。

它只占据屏幕的一半,因为它可以拉伸到其子元素所需的大小。


您正在使用以下代码将container居中:

1
2
3
4
position: absolute
top: 50%
left: 50%
transform: translate(-50%, -50%)

当给元素一个position: absolute并给出一个left: 50%时,它会自动移动,并将其后继的子代(如果子代没有position: absolute)从左侧移到50%

如果要使容器占据整个宽度,则必须删除以下内容:

1
2
3
4
position: absolute
top: 50%
left: 50%
transform: translate(-50%, -50%)


我对您的css进行了一些更改。希望对您有所帮助:

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
#main {
  z-index: 0;
  width: 100%;
  min-height:100%;
  background: #FFFFFF;
  left: 0px;
  top: 0px;
  padding: 50px 0px;
  text-align: center;
  }
  div.container{
    margin-left: 0 auto;
    display: block;
    max-height: 100%;
    margin: 0 auto;
    width: auto;
    max-width: 100%;
    overflow-y: auto;
    overflow-x: hidden;
    text-align: left;
    }

div.box{
    width: 240px;
    height: 200px;
    margin-left: auto;
    margin-right: auto;
    border: 1px solid #5774FF;
    padding: 19px;
    margin-bottom: 10px;
    display: block;
    box-shadow: 1px 1px 4px #CCC;
    float: none;}
1
2
3
4
5
6
7
            <form action="/save" method="post">
                <input type="text" placeholder="code" name="name"/>
                <select name="education">
                    <option value="3">option 3</option>
                </select>
                <button type="submit">save</button>
            </form>


max-width将防止元素的宽度超出指定的范围,但不会使其变得更宽。