一个高度固定的div里面有好几个p标签 当p标签过多超出div的高度时 让div最底部显示省略号 同时超出div的不显示 当我hover时使用css让div不再是固定的高度 能够将所有内容显示出来 请你给出五种写法
时间: 2023-06-15 07:03:19 浏览: 50
以下是五种实现方式:
1. 使用 CSS 的 text-overflow 属性和 overflow 属性实现:
```html
<div class="container">
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
</div>
```
```css
.container {
height: 100px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.container:hover {
height: auto;
}
```
2. 使用 CSS 的 max-height 属性和 :after 伪元素实现:
```html
<div class="container">
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
</div>
```
```css
.container {
position: relative;
max-height: 100px;
overflow: hidden;
}
.container:after {
content: "...";
position: absolute;
bottom: 0;
right: 0;
background-color: white;
padding: 0 5px;
}
.container:hover {
max-height: none;
}
.container:hover:after {
display: none;
}
```
3. 使用 JavaScript 动态计算高度并添加省略号:
```html
<div class="container" id="container">
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
</div>
```
```css
.container {
height: 100px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
```
```javascript
const container = document.getElementById("container");
const ps = Array.from(container.getElementsByTagName("p"));
const maxHeight = 100;
let totalHeight = 0;
for (let i = 0; i < ps.length; i++) {
totalHeight += ps[i].offsetHeight;
if (totalHeight > maxHeight) {
ps[i].style.display = "none";
container.classList.add("has-ellipsis");
break;
}
}
```
```css
.container.has-ellipsis:after {
content: "...";
position: absolute;
bottom: 0;
right: 0;
background-color: white;
padding: 0 5px;
}
.container:hover {
height: auto;
}
.container:hover:after {
display: none;
}
```
4. 使用 CSS 的 clamp() 函数实现:
```html
<div class="container">
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
</div>
```
```css
.container {
height: clamp(50px, 100px, auto);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
```
```css
.container:hover {
height: auto;
}
```
5. 使用 CSS 的 grid 布局实现:
```html
<div class="container">
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
</div>
```
```css
.container {
display: grid;
grid-template-rows: repeat(auto-fit, minmax(20px, 1fr));
height: 100px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
```
```css
.container:hover {
height: auto;
}
```
以上是五种实现方式,可以根据实际情况选择适合自己的方式。