html - 多边形 div 容器中的中心元素
问题描述
目前我有一个 div 容器,里面有文本。
div {
height: 200px;
background: red;
}
p {
text-align: center;
}
<div>
<p>
Text goes here
</p>
</div>
我希望这个 div 容器是一个平行四边形,里面有一个垂直居中的文本。
div {
height: 200px;
background: red;
clip-path: polygon(0 25%, 100% 0, 100% 25%, 0 50%);
}
p {
text-align: center;
}
<div>
<p>
Text goes here
</p>
</div>
正如您在此处看到的,文本完全消失了,因为 css 仅适用于 div 容器。
如何使文本出现在这个平行四边形的垂直中心?
编辑:
不知道有没有用
clip-path: polygon(0 25%, 100% 0, 100% 25%, 0 50%);
是创建倾斜的 div 容器的最佳方法。
解决方案
使用渐变创建作为背景的形状,您只需使用任何常用方式将文本居中即可。您将获得比 更好的支持clip-path
。
div.container {
height: 120px;
line-height:120px;
background-image:
/*Top triangle*/
linear-gradient(to bottom right,transparent 49%,red 51%),
/*Bottom triangle*/
linear-gradient(to top left,transparent 49%,red 51%);
background-position:top, bottom; /* One on the top and the other on the bottom*/
background-size:100% 50%; /*both will be 100% width and 50% height*/
background-repeat:no-repeat; /*don't repeat*/
}
p {
text-align: center;
}
<div class="container">
<p>
Text goes here
</p>
</div>
如果你想更好地依赖clip-path
这些值来覆盖整个 div,你只需要调整 div 的高度来控制形状的高度:
div.container {
height: 120px;
line-height:120px;
background:red;
-webkit-clip-path: polygon(0 50%, 100% 0%, 100% 50%, 0% 100%);
clip-path: polygon(0 50%, 100% 0%, 100% 50%, 0% 100%);
}
p {
text-align: center;
}
<div class="container">
<p>
Text goes here
</p>
</div>
推荐阅读
- ruby-on-rails - NameError:未初始化的常量 GoogleService::Google with google-api-client gem
- azure-functions - Azure 持久编排 - 编排完成后引发事件
- python-3.x - 如何在python中使用正则表达式获取文件中的所有匹配组
- fonts - 如果系统不支持字体,如何创建字体别名?
- c - OSDev - 在“docker”中使用“make”命令时出错
- visual-studio - omptarget.dll 未找到
- python - 另一个 pandas .drop 内存泄漏
- hive - Hive 是否需要显式命令才能将数据从 HDFS 加载到表中
- python - 从响应对象获取文件内容
- r - 是否可以使用 Wilcoxon 检验比较不同子组内的组前后,用 gtsummary 生成 gtsummary 表?