Search code examples
htmlcssalignment

Vertically and Horizontally Align div within div with :after selector


I have this HTML & CSS code :

html {
  overflow-x: hidden;
  overflow-y: hidden;
}
body {
  margin: 0;
}
.triangle-down {
  width: 90%;
  height: auto;
  padding-left: 50%;
  padding-top: 50%;
  overflow: hidden;
}
.triangle-down:after {
  content: "";
  display: block;
  width: 0;
  height: 0;
  margin-left: -500px;
  margin-top: -500px;
  border-left: 500px solid transparent;
  border-right: 500px solid transparent;
  border-top: 500px solid #9CE08F;
}
div {
  float: left;
  margin: 0.5%;
}
<div class="triangle-down">
  <div>&nbsp;</div>
</div>

And I am trying to make the div within the triangle-down to align vertically and horizontally. Alternatively, I can just use text instead of div and align it. In this case I am using the :after selector and I cannot change the CSS in a way to make it work. I know how to do it using position:relative and position:absolute or even the display:inline-block.

But in this case, it is more complex. If I change the CSS for triangle-down, then I am not getting a triangle anymore.

I want to have something like this :

enter image description here


Solution

  • .btn {
        position: relative;
        display: inline-block;
        height: 0px; width:100%;
        text-align: center;
        color: white;
        background: gray;
        line-height: 50px;
        text-decoration: none;
        padding-bottom:42%;
        background-clip:content-box;
        overflow:hidden;
    }
    .btn:after {
        content: "";
        position: absolute;
        top:0px; left: 0;
        background-color:inherit;
        padding-bottom:50%; width:57.7%;
        z-index:-1;
        
        -webkit-transform-origin:0 0;
        -ms-transform-origin:0 0;
        transform-origin:0 0;
        
        -webkit-transform: rotate(-30deg) skewX(30deg);;
        -ms-transform: rotate(-30deg) skewX(30deg);
        transform: rotate(-30deg) skewX(30deg);
    }
    /** FOR THE DEMO
    body{background: url('http://lorempixel.com/output/people-q-c-640-480-1.jpg');background-size:cover;} **/
    <a href="#" class="btn">Hello!</a>