Cloudy Skies
Cloudy Skies

Reputation: 63

How to center arrow created with border and transform?

How to centre this type of arrows? I tried with transform but it didn't work. Ex:

.test {
  width: 500px;
  height: 500px;
  background: pink;
  position: relative;
}

.test::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    display: inline-block;
    width: 60px;
    height: 60px;
    border-right: 2px solid red;
    border-bottom: 2px solid red;
    transform: rotate(135deg) translate(-50%, -50%);
}
<div class="test"></div>

Upvotes: 0

Views: 606

Answers (2)

Matt Croak
Matt Croak

Reputation: 2888

You can simplify the CSS for arrow::before by making arrow by using the CSS in the code snippet.

.test {
  width: 500px;
  height: 500px;
  background: pink;
  display: flex;
  align-items:center;
  justify-content: center;
  /*positiom: relative;*/
}

.test::before {
    content: '';
  /*position: absolute;*/
   /*top: 50%;*/
   /*left: 50%;
  /*display: inline-block; */
    width: 60px;
    height: 60px;
    border-right: 2px solid red;
    border-bottom: 2px solid red;
    transform: rotate(135deg) translate(-20%, -20%);
}
<div class="test"></div>

Aside from saving you a few lines of code you don't have to mess around with absolute positioning in case you want to make adjustments in the future.

Upvotes: 2

Temani Afif
Temani Afif

Reputation: 272806

Translate then rotate, order is important

.test {
  width: 500px;
  height: 500px;
  background: 
   linear-gradient(black,black) center/10px 10px no-repeat,
   pink;
  position: relative;
}

.test::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    display: inline-block;
    width: 60px;
    height: 60px;
    border-right: 2px solid red;
    border-bottom: 2px solid red;
    transform: translate(-50%, -50%) rotate(135deg);
}
<div class="test"></div>

And if you want to consider only the arrow, adjust the left position:

.test {
  width: 500px;
  height: 500px;
  background: 
   linear-gradient(black,black) center/10px 10px no-repeat,
   pink;
  position: relative;
}

.test::before {
    content: '';
    position: absolute;
    top: 50%;
    left: calc(50% + 15px);
    display: inline-block;
    width: 60px;
    height: 60px;
    border-right: 2px solid red;
    border-bottom: 2px solid red;
    transform: translate(-50%, -50%) rotate(135deg);
}
<div class="test"></div>

Or the translation:

.test {
  width: 500px;
  height: 500px;
  background: 
   linear-gradient(black,black) center/10px 10px no-repeat,
   pink;
  position: relative;
}

.test::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    display: inline-block;
    width: 60px;
    height: 60px;
    border-right: 2px solid red;
    border-bottom: 2px solid red;
    transform: translate(-25%, -50%) rotate(135deg);
}
<div class="test"></div>

Upvotes: 0

Related Questions