CSS automatically hides when content exceeds the limit
CSS Auto-Hide Beyond Content
In web development, content often exceeds the size of its container. In these cases, CSS is needed to automatically hide the excess content. This article explains in detail how to use CSS to automatically hide an element when its content overflows.
Overflow Property
In CSS, the Overflow
property controls how an element behaves when its content overflows its container. The overflow
attribute has the following values:
visible
: Default value. Content will be visible when it exceeds the container.hidden
: Content will be hidden when it exceeds the container.scroll
: Displays scroll bars when the content exceeds the container.auto
: Displays scroll bars only when needed when the content exceeds the container.
Example
To demonstrate the effect of the overflow
attribute, let’s create a simple HTML structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Overflow Example</title>
<style>
.container {
width: 200px;
height: 100px;
border: 1px solid #ccc;
overflow: hidden;
}
.container-inner {
width: 250px;
height: 120px;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<div class="container">
<div class="container-inner">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec Nulla urna. Donec in tristique mauris. Nunc aliquet neque eget leo aliquet, ut euismod enim auctor. sit amet lectus quis nisi pulvinar semper. Nam eu aliquam velit, sed iaculis risus.
</div>
</div>
</body>
</html>
In the above example, we created a container .container
with a width of 200px and a height of 100px, and set the overflow: hidden;
attribute. The width of the .container-inner
element inside the container is 250px and the height is 120px, exceeding the bounds of the .container
element.
When the browser renders the above code, the .container-inner
element exceeds the bounds of the .container
element. However, because we’ve set the overflow: hidden;
property, the excess portion is hidden.
Result Display
Running the above example code, you’ll see a container displayed on the page. The content inside the container exceeds the container’s size, but the excess is automatically hidden, leaving only the content within the container’s bounds visible.
Summary
By using the overflow: hidden;
property, we can easily achieve an automatic hiding effect when content exceeds the container’s size. This is a common problem in web development, especially in specific layout designs.