使用 CSS Overflow 属性

cssweb developmentfront end technology更新于 2025/1/6 21:00:17

当用户想要在较小的容器中显示较大的内容而不调整内容大小时,CSS overflow 属性非常有用。此属性允许用户剪切内容,提供滚动条以查看剪切的内容,并将内容渲染到容器外部,因此得名 overflow。

语法

以下是 CSS Overflow 属性 − 的语法

Selector {
   overflow: /*value*/
}

以下是 CSS Overflow 属性的值 −

Sr.NoValue &说明
1visible
这是默认值,内容不被裁剪并渲染在元素框之外,因此属性名称为 overflow
2hidden
它会裁剪溢出元素框的内容,裁剪后的内容不可见
3scroll
它会裁剪溢出元素框的内容,裁剪后的内容可见,因为滚动条也会随内容一起渲染
4auto
它会自动渲染滚动条以查看溢出的内容内容

我们来看一个 CSS 溢出属性的示例 −

示例

<!DOCTYPE html>
<html>
<head>
<title>CSS Overflow</title>
<style>
form {
   width:70%;
   margin: 0 auto;
   text-align: center;
}
* {
   padding: 2px;
   margin:5px;
}
input[type="button"] {
   border-radius: 10px;
}
#containerDiv {
   margin: 0 auto;
   height: 100px;
   width: 100px;
   overflow: auto;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>CSS Overflow</legend>
<div id="containerDiv">
<img id="image" src="https://www.cainiaomax.com/hadoop/images/hadoop-mini-logo.jpg">
</div>
<input type="button" onclick="fitHeight()" value="Remove Scrollbars">
</fieldset>
</form>
<script>
var divDisplay = document.getElementById("divDisplay");
var imgSelect = document.getElementById("image");
var containerDiv = document.getElementById("containerDiv");
function fitHeight() {
   containerDiv.style.height = imgSelect.height+'px';
   containerDiv.style.width = imgSelect.width+'px';
   containerDiv.style.overflow = 'hidden';
}
</script>
</body>
</html>

输出

点击任何按钮之前 −

点击‘移除滚动条’按钮之后 −

让我们看另一个 CSS 溢出属性的示例 −

示例

<!DOCTYPE html>
<html>
<head>
<title>CSS Overflow</title>
<style>
form {
   width:70%;
   margin: 0 auto;
   text-align: center;
}
* {
   padding: 2px;
   margin:5px;
}
input[type="button"] {
   border-radius: 10px;
}
#containerDiv {
   margin: 0 auto;
   height: 110px;
   overflow: scroll;
}
</style></head>
<body>
<form>
<fieldset>
<legend>CSS Overflow</legend>
<div id="containerDiv">
This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text.</div>
<input type="button" onclick="add()" value="Remove Scrollbars">
</fieldset>
</form>
<script>
function add() {
   document.querySelector('#containerDiv').style.overflow = "hidden";
}
</script>
</body>
</html>

输出

点击"移除滚动条"按钮之前 −

点击"移除滚动条"按钮之后 −


相关文章


有用资源