Home > OS >  Center an absolute element below a div?
Center an absolute element below a div?

Time:08-22

I'm trying to center a pargraph below a div (could be a square image for the matter). I understand that the easiest way to do it is to contain both the div and the text below it in a single container and use text-align, but in this instance I have a limitation where I cannot let the small image be contained in a container wider than that image.

Without centering the text it looks like this:

enter image description here

My code:

HTML:

<div ></div>
<p >This text is a bit long</p>

CSS:

body {
  padding: 5rem;
}
.block {
  background-color: blue;
  width: 80px;
  height: 80px
}

.label {
  
}

Codepen: https://codepen.io/omerh3/pen/oNqVjvV

The reason why I cannot let the image be in a container is that I'm using ReactFlow where the handles should connect to the sides of the image without a gap. If I put the image and the text inside a div, the div will take the width of the text and thus it will naturally be wider than the image.

I tried centering the text below the image with absolute positioning, but with different paragraphs sizes, it won't be persistent in the center. Is there a away to achieve this without inserting the image/square and the text inside one div?

One last thing: the width of the image if constant, for example 100px

CodePudding user response:

one way to do this is to get the coordinates of your two elements and then add margin-left: to adjust the position of the span

let divOffsets = document.getElementById('a').getBoundingClientRect();
let divRight = divOffsets.right;
let divLeft = divOffsets.left;
console.log(divLeft,divRight)

let spanOffsets = document.getElementById('b').getBoundingClientRect();
let spanRight = spanOffsets.right;
let spanLeft = spanOffsets.left;
console.log(spanLeft,spanRight)

let divCenter = divLeft   divRight / 2
console.log(divCenter)

let offset = divCenter - (spanLeft   spanRight / 2) 
offset = offset   "px"

document.getElementById('b').style.marginLeft = offset;
body {
  padding: 5rem;
  border:solid 1px red;
  position:relative;
}
.block {
  background-color: blue;
  width: 80px;
  height: 80px;
  
}

span{
position:absolute;
}
<div id = 'a'></div>
<span id = 'b' >1234</span>

CodePudding user response:

Do you mean something like this??

body {
  padding: 5rem;
}
.block {
  background-color: blue;
  width: 80px;
  height: 80px;
  margin:0 auto;
  
}

p.label {text-align: center}
<div ></div>
<p >This text is a bit long</p>

  • Related