多边形div容器中的中心元素

问题描述 投票:4回答:1

目前我有一个带有文本的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容器的最佳方法。

html css css3
1个回答
4
投票

使用渐变创建形状作为背景,你只需要center the text using any common way。你会得到比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>
© www.soinside.com 2019 - 2024. All rights reserved.