在父div内对角线排列2个div

2022-04-02 00:00:00 reactjs html css css-grid

我正在尝试将两个div安排在父div中,这样看起来父div就像是被对角分成了两部分。下图将显示所需内容

这是我尝试过的代码。

App.js

import React, { Component } from "react";
import "./App.css";

class InnerMainDiv extends Component {
  constructor() {
    super();
    this.section = React.createRef();
  }
  componentDidMount() {
    this.handleResize();
    window.addEventListener("resize", this.handleResize);
  }
  componentWillUnmount() {
    window.addEventListener("resize", null);
  }
  handleResize = (WindowSize, event) => {
    let h = this.section.current.clientHeight;
    let w = this.section.current.clientWidth;
    let angle = Math.atan(h / w) * 57.29577;
    let rotateProperty = "rotate(" + angle + "deg)";
    this.section.current.style.webkitTransform = rotateProperty;
    this.section.current.style.transform = rotateProperty;
    this.section.current.style.mozTransform = rotateProperty;
  };
  render() {
    return (
      <div className="maindiv">
        <section ref={this.section}>
          <div href="#1" />
        </section>
        <section ref={this.section}>
          <div href="#2" />
        </section>
      </div>
    );
  }
}

export default InnerMainDiv;

App.css

html,
body,
div {
  height: 100%;
  width: 100%;
  padding: 0;
  margin: 0;
}

div {
  overflow: hidden;
  position: relative;
}

section {
  position: absolute;
  top: -100%;
  height: 5000vw;
  width: 5000vh;
  background: #ccc;
  -webkit-transform-origin: 0 0;
  -moz-transform-origin: 0 0;
  transform-origin: 0 0;
}

section + section {
  background: #666;
  top: 0%;
}

section div {
  display: block;
  width: 100%;
  height: 100%;
  cursor: pointer;
}

对如何实现这一点有什么想法或建议吗?


解决方案

您可以使用clip-path来实现此目的:

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
.container {
  width: 200px;
  height: 200px;
  position: relative;
}

.container > * {
  height: 100%;
  background: red;
}

.container :last-child {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  background: blue;
  -webkit-clip-path: polygon(0 0, 100% 0%, 100% 100%);
  clip-path: polygon(0 0, 100% 0%, 100% 100%);
}
<div class="container">
  <div></div>
  <div></div>
</div>

但如果您想要更多的浏览器支持,您可以像这样使用旋转:

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
.container {
  width: 200px;
  height: 200px;
  position: relative;
  overflow:hidden;
}

.container > * {
  height: 100%;
  background: red;
}

.container :last-child {
  position: absolute;
  top: 0;
  left: 0;
  width: 141%; /* = 1.41 * 100% --> 1.41 = sqrt(2) */
  height: 141%;
  background: blue;
  transform-origin:top left;
  transform:rotate(-45deg);
}
<div class="container">
  <div></div>
  <div></div>
</div>

相关文章