Home > Enterprise >  Css, known height: formula to absolute place an element so that "fits" the middle of a squ
Css, known height: formula to absolute place an element so that "fits" the middle of a squ

Time:06-02

I know the height of the tree buttons (3rem, 3.75rem, 4.25rem). I need to place the i icon element at the right, in the middle of an imaginary square positioned at the right end of the button itself (purple area).

I've used right: 0 along with translateX(-50%) but it seems working only for the middle button (by chance). Any help is much appreciated.

.btn > i {
  position: absolute;
  z-index: 1;
  top: 50%;
  right: 0;
  transform: translate(-100%, -50%);
}

enter image description here

CodePudding user response:

If you know the dimensions of the icon, then you can use calculate()

lets say the icon is 10x20px

.btn > i {
  width: 20px;
  height: 10px;
  position: absolute;
  z-index: 1;
  top: calculate(50% - 5px);
  right: calculate(50% - 10px);
}
.btn > i:after {
  display: block;
  width: 20px;
  height: 10px;
}

If you would like to avoid the absolute positioning, you can use flexbox:

.btn {
  display: flex;
  justify-content: center;
  align-items: center;
}

this will effectively center any single element inside of flexbox

CodePudding user response:

Just with a couple simple calc()'s and a few CSS variables this is quite simple

.btn-sm {
  --btnSize: 3.00rem;
}
.btn-md {
  --btnSize: 3.75rem;
}
.btn-lg {
  --btnSize: 4.25rem;
}

.btn {
  border: 2px solid purple;
  color: purple;
  display: inline-block;
  font-family: sans-serif;
  margin-bottom: 1rem;
  position: relative;
  
  border-radius: var(--btnSize);
  line-height: var(--btnSize);
  height: var(--btnSize);
  padding: 0 calc( var(--btnSize)   2rem ) 0 2rem;
}
.btn::before,
.btn::after {
  position: absolute;
}
.btn::before {
  inset: 0 0 0 auto;

  content: "";
  background: purple;
  border-radius: 100%;
  width: var(--btnSize);
}
.btn::after {
  inset: 0 calc( var(--btnSize) / 2 ) 0 auto;

  color: white;
  content: "→";
  
  transform: translateX(50%);
}
<div >Approfondisci</div><br>
<div >Approfondisci</div><br>
<div >Approfondisci</div><br>

  •  Tags:  
  • css
  • Related