如何用 CSS 制作 div 三角形的顶部和底部?

How to make top and bottom of div triangle with CSS?

现在我得到了这个:

三个 DIV。顶部的第一个是三角形,中间的是正常的 DIV 没有任何形状,第三个在底部也是三角形。所有形状都是通过 CSS (border-transparency)

形成的

我想将三个 DIV 合并为一个而不丢失整个构造的形状。这可能吗?

这是我的 HTML-代码:

<div id="triangle1"></div> /* triangle at the top */
<div id="center">
<p>Text Text Text</p>
<div id="triangle2"></div> /* triangle at the bottom */

这里是 CSS-代码:

#center {
    background-color: #E0E0E0;
    position: absolute;
    width: auto;
    height: auto;
    top: 100px;
    left: 20%;
    right: 20%;
    text-align: justify;
    padding-left: 3%;
    padding-right: 3%;
}

#triangle1 {
    width: 0;
    height: 0;
    top: 20px;
    border-style: solid;
    border-width: 0 1143px 80px 0px;
    border-color: transparent transparent #E0E0E0 transparent;
    left: 20%;
    right: 20%;
    position: absolute;
}

#triangle2 {
    width: 0;
    height: 0;
    top: 312px;
    border-style: solid;
    border-width: 80px 0 0 1152px;
    border-color: #E0E0E0 transparent transparent transparent;
    left: 20%;
    right: 20%;
    position: absolute;
}

我想将#triangle1 和#triangle2 的代码合并到#center 中而不丢失它现在的外观(如屏幕截图所示)。 但是怎么办?

谢谢你。

You could use CSS transforms to accomplish this.

transform: skewY(3deg);

转换父项有一个副作用,它的后代(带文字的段落)也会倾斜。一个简单的解决方法是反转后代元素的转换。

Here is a quick demo.

You might need to add browser-specific prefixes 对于旧版浏览器:

-moz-transform: skewY(3deg);
-webkit-transform: skewY(3deg);
-o-transform: skewY(3deg);
-ms-transform: skewY(3deg);
transform: skewY(3deg);