RBlair
RBlair

Reputation: 67

Crop Rotated Shape In HTML

I have a colored div that has been rotated 45 degrees and was wondering if there is way to crop the edges of it so that it fits within a certain boundry. (eg: a 45 degree line through a square that is cut off where it touches the square)

Here is the code:

#parent {
  width: 200px;
  height: 200px;
  border: 1px solid black;  
}
#child {
  -ms-transform: rotate(45deg);
  -webkit-transform: rotate(45deg);
  transform: rotate(45deg); 
}
.red_stripe {
  width: 500px;
  height: 50px;
  background-color: red;
  position:absolute;
}
#gap {
  height:100px;
}
<div id = "parent">
  <div id = "child">
    <div class = "red_stripe"></div>
    <div id = "gap"></div>
    <div class = "red_stripe"></div>
  </div>
</div>

I have recreated this in JSFIDDLE: http://jsfiddle.net/RBlair/s9qusfvv/2/

So what should happen is that the red bar should be cut off where it meets the black border on the right and along the bottom sides (I am not worried about it exceeding the boundary at the top or left, just the right side and the bottom)

Upvotes: 4

Views: 1638

Answers (2)

misterManSam
misterManSam

Reputation: 24692

Let's reduce the HTML required

Pseudo element background

Use overflow: hidden, but create the lines with a ::before pseudo element and no extra HTML.

We can use:

  • inner box shadow to create the lines (useful as it does not take up space like a border)

  • position: absolute to position the :before along with a percentage height, width, left and right

  • position: relative on the div so that the pseudo element is positioned in relation to it

Complete Example

div {
  width: 200px;
  height: 200px;
  border: 1px solid black;
  position: relative;
  overflow: hidden;
}
div::before {
  content: '';
  display: block;
  position: absolute;
  top: 0;
  left: -50%;
  box-shadow: inset 0 0 0 50px #F00;
  height: 100%;
  width: 200%;
  transform: rotate(45deg);
  z-index: -1;
}
<div class="box">

</div>

Upvotes: 3

j08691
j08691

Reputation: 207861

Add overflow:hidden to #parent

#parent {
  width: 200px;
  height: 200px;
  border: 1px solid black;
  overflow: hidden;
}
#child {
  -ms-transform: rotate(45deg);
  -webkit-transform: rotate(45deg);
  transform: rotate(45deg);
}
.red_stripe {
  width: 500px;
  height: 50px;
  background-color: red;
}
#gap {
  height: 100px;
}
<div id="parent">
  <div id="child">
    <div class="red_stripe">
    </div>

    <div id="gap">
    </div>

    <div class="red_stripe">
    </div>
  </div>
</div>

Upvotes: 4

Related Questions