使用 CSS 处理溢出内容

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

我们可以使用 CSS overflow 属性来管理/处理元素的溢出内容。此属性允许用户剪切内容,提供滚动条以查看剪切的内容,并将内容渲染到容器之外,因此得名 overflow。

语法

以下是 CSS Overflow 属性的语法 −

Selector {
   overflow: /*value*/
}

让我们看一个 CSS overflow 属性的例子 −

示例

<!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>

输出

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

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

让我们看另一个关于 CSS overflow 属性的示例 −

示例

<!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/sas/images/sas-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>

输出

点击任何按钮之前 −

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


相关文章


有用资源