0

I am trying to create a triangle shape to be within its parent with a 100% width of whatever the parent's width would be.

This is what I tried:

* {
margin:0;
padding:0;
}

.test {
width: 500px;
height: 500px;
background-color: green;
position: relative;
box-sizing: border-box;
}

.triangle-topleft {
      width: 0;
      height: 0;
      border-top: 100px solid red;
      border-right: 100vw solid transparent;
      position: absolute;
      box-sizing: border-box;
    }
<div class="test">
  <div class="triangle-topleft"></div>
</div>

So, as you can see, I have the child div within the parent (absolute position). Why is the triangle shape still going out of the parent? Is there a way where I can make the triangle be 100% width?

Most of the answers here are about box-sizing: border-box , but it does not work.

Anyone knows how to fix this OR is there a better way of making a top triangle other than using borders?

Gosi
  • 2,004
  • 3
  • 24
  • 36

1 Answers1

1

Your code does not do what you intend it to be: 100vw is not the parent width, but the viewport width. So it is expected that the shape will grow outside of the parent bounds. If you want to keep it within bounds, you will need to set the border-right width to 500px:

* {
margin:0;
padding:0;
}

.test {
width: 500px;
height: 500px;
background-color: green;
position: relative;
box-sizing: border-box;
}

.triangle-topleft {
      width: 0;
      height: 0;
      border-top: 100px solid red;
      border-right: 500px solid transparent;
      position: absolute;
      box-sizing: border-box;
    }
<div class="test">
  <div class="triangle-topleft"></div>
</div>

However, this can be troublesome since that means you need to hardcode the parent width as the border-right-width. Another solution will be to simply use CSS linear gradient:

* {
  margin: 0;
  padding: 0;
}

.test {
  width: 500px;
  height: 500px;
  background-color: green;
  position: relative;
  box-sizing: border-box;
}

.triangle-topleft {
  width: 100%;
  height: 100px;
  position: absolute;
  background-image: linear-gradient(to bottom right, red 50%, transparent 50%);
}
<div class="test">
  <div class="triangle-topleft"></div>
</div>
Terry
  • 63,248
  • 15
  • 96
  • 118