首页 > 解决方案 > 多边形 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 容器的最佳方法。

标签: htmlcss

解决方案


使用渐变创建作为背景的形状,您只需使用任何常用方式将文本居中即可。您将获得比 更好的支持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>


推荐阅读