overflow和text-overflow的用法
一、overflow
规定了内容超出元素框时发生的事情。
有五种属性值是:
visible:默认值,内容不会被修剪,会超出元素框显示。
hidden:内容会被修剪,超出元素框的部分会被隐藏。
scroll:内容会被修剪,但浏览器会显示滚动条以查看其余内容。
auto:如果内容被修剪,浏览器就会显示滚动条以查看其余内容。
inherit:从父元素继承overflow的值。
举例:
1.overflow:hidden用在隐藏超出当前元素框的内容,例如
<body>
<div class="a">我是大聪明我是大聪明我是大聪明我是大聪明我是大聪明我是大聪明我是大聪明我是大聪明我是大聪明我是大聪明</div></body>
<style>
.a{
width: 100px;
height: 100px;
background-color:red;
overflow: hidden;
}
</style>
见图:
2.overflow:scroll用在以滚动条的方式显示超出元素框的内容,但是不论内容是否超出元素框,都会有滚动条的位置默认显示出来。
<body>
<div class="a">我是a大聪明我是a大聪明我是a大聪明我是a大聪明我是a大聪明我是a大聪明我是a大聪明我是a大聪明我是a大聪明我是a大聪明</div>
<br><br>
<div class="b">我是b大聪明我是b大聪明</div>
</body>
<style>
.a{
width: 100px;
height: 100px;
background-color:red;
overflow: scroll;
}
.b{
width: 100px;
height: 100px;
background-color:red;
overflow: scroll;
}
</style>
见图
3.overflow:auto如果内容被修剪则会显示滚动条以查看其余内容,否则不会。
<body>
<div class="a">我是a大聪明我是a大聪明我是a大聪明我是a大聪明
我是a大聪明我是a大聪明我是a大聪明我是a大聪明我是a大聪明我是a大聪明</div>
<br><br>
<div class="b">我是b大聪明我是b大聪明</div>
</body>
<style>
.a{
width: 100px;
height: 100px;
overflow:auto;
background-color: red;
}
.b{
width: 100px;
height: 100px;
overflow: auto;
background-color: red;
}
</style>
见图
4.overflow:inherit子元素继承父元素的Overflow属性值
<body>
<div class="a">我是a大聪明我是a大聪明我是a大聪明我是a大聪明
我是a大聪明我是a大聪明我是a大聪明我是a大聪明我是a大聪明我是a大聪明
<div class="b">我是b大聪明我是b大聪明我是b大聪明
我是b大聪明我是b大聪明我是b大聪明我是b大聪明</div></div>
</body>
<style>
.a{
width: 150px;
height: 200px;
overflow:hidden;
background-color: red;
}
.b{
width: 100px;
height: 100px;
overflow:inherit ;
background-color: blue;
}
</style>
见图
二、text-overflow
规定当文本溢出包含元素时发生的事情。
有三个属性值
clip:裁剪文本
ellipsis:使用省略号代表被修剪的文本
string:使用特定字符串代表被修剪的文本
举例:
<body>
<div class="a">我是大聪明我是大聪明我是大聪明我是大聪明</div>
<br><br>
<div class="b">我是大聪明我是大聪明我是大聪明我是大聪明</div>
</body>
<style>
.a{
width: 200px;
height: 20px;
font: 8px/20px arial;
border: 1px solid black;
overflow: hidden; /* 超出元素框部分隐藏 */
text-overflow: clip; /* 超出的文本被裁剪 */
white-space: nowrap;/* 强制文本在同一行表示 */
}
.b{
width: 200px;
height: 20px;
font: 8px/20px arial;
border:1px solid black;
overflow: hidden;
text-overflow: ellipsis;/* 超出的文本用省略号表示 */
white-space: nowrap;/* 强制文本在同一行表示 */
}
</style>
见图
PS:在掌握text-overflow的属性时同步要掌握的是文本换行(word-wrap)属性和空白符(white-space)属性,他们经常会一起使用。