TRomesh
TRomesh

Reputation: 4481

Arrange 2 divs diagonally inside a parent div

I'm trying to arrange 2 divs inside a parent div so that is looks like the parent div is being divided into 2 parts diagonally. The diagram below will show what is required

enter image description here

This is the code i have tried.

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;
}

Any ideas or suggestions on how to achieve this?.

Upvotes: 1

Views: 458

Answers (1)

Temani Afif
Temani Afif

Reputation: 274106

You can use clip-path to achieve this:

.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>

But in case you want more browser support you can use rotation like this:

.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>

Upvotes: 1

Related Questions