auto
CSS属性的值是什么意思。当 CSS 属性的值设置为 时会发生什么auto
?
64246 次
4 回答
96
所述属性的值根据元素的内容或上下文自动调整。
例如,一个块级元素height: auto
会随着包含更多文本而变得更高。再举一个例子,一个块元素margin: 0 auto
的左右边距会增加,直到它沿着视口的 y 轴居中。
这实际上取决于您赋予价值的属性,不同的属性根据内容和上下文表现不同。
于 2010-12-17T15:16:15.267 回答
16
auto 表示自动调整。我使用 auto 的最常见原因是:
margin: 0 auto;
使元素居中。
请注意:如果未声明大小,则它将不起作用。
示例 1:div 不居中,auto 不起作用
<style>
.cont {
margin: 0 auto;
}
</style>
<div class="cont"></div>
示例 2:div 以页面为中心
<style>
.cont {
width: 1000px;
margin: 0 auto;
}
</style>
<div class="cont"></div>
于 2013-03-21T00:19:30.407 回答
2
它确实取决于您使用的属性。例如,块宽度设置自动将扩展其父元素的全部空间。但块高度设置自动只会扩展其内容所需的空间。
<style>
#outer{
width: 500px;
height: 500px;
border: solid 2px black;
}
#inner{
width: auto;
height: auto;
background-color: aqua;
}
</style>
<div id="outer">
<div id="inner">content</div>
</div>
于 2016-05-27T06:24:48.407 回答
2
这取决于。以下是该auto
值的一些常见用法。
高度:自动
元素高度取决于其子元素的高度。
.container {
width: 250px;
height: auto;
background: gray;
}
.item {
width: 50px;
background: orange;
}
<div class="container">
<div class="item">
child content
</div>
</div>
宽度:自动
对于块级元素,宽度是容器宽度减去元素的水平间距(边距+边框+填充)。
.container {
width: 250px;
height: 150px;
background: gray;
}
.item {
width: auto;
margin: 0 10px;
border-left: 5px solid;
border-right: 5px solid;
padding: 0 10px;
background: orange;
font-size: 14px;
}
<div class="container">
<div class="item">
calculated content width is 200px
</div>
</div>
请注意,当容器使用 align 进行伸缩时,行为会有所不同。
.container {
width: 250px;
height: 150px;
display: flex;
flex-direction: column;
background: gray;
}
.item {
width: auto;
background: orange;
/* comment out next line to make width take parent's width */
align-self: start;
}
<div class="container">
<div class="item">
child
</div>
</div>
保证金:自动
水平居中块级元素。
.container {
width: 250px;
height: 150px;
background: gray;
}
.item {
width: 32px;
margin: 0 auto;
background: orange;
}
<div class="container">
<div class="item">
child
</div>
</div>
将一个元素推到 flex 容器内的末尾。
.container {
width: 300px;
height: 150px;
display: flex;
background: gray;
}
.item {
width: 50px;
height: 25px;
background: orange;
border-left: 1px solid;
}
.item3 {
margin-left: auto;
}
<div class="container">
<div class="item">
child 1
</div>
<div class="item">
child 2
</div>
<div class="item item3">
child 3
</div>
</div>
于 2021-01-10T18:34:34.520 回答