Home > database >  Child element not positioned correctly relative to parent element?
Child element not positioned correctly relative to parent element?

Time:01-05

I have code blocks on my website that look like this:

Image

This pre block has a child button, as shown below.

Image

I am applying the following CSS to the button element:

pre[class*="language-"] button {
    position: absolute;
    top: 5px;
    right: 5px;

    font-size: 0.9rem;
    padding: 0.15rem;
    border: ridge 1px #7b7b7c;
    border-radius: 5px;
    text-shadow: #c4c4c4 0 0 2px;
}

code[class*="language-"] button:hover {
    cursor: pointer;
    background-color: #bcbabb;
}

However, the button appears to be located top: 5px; right: 5px; of the HTML document instead of the pre (ignore the toggle).

Image

I removed the positioning from the button, and it now appears kinda correctly (at least somewhat in the right place) like so:

Image

I can't figure it out why the CSS isn't correctly positioning it...

CodePudding user response:

absolute
The element is removed from the normal document flow, and no space is created for the element in the page layout. It is positioned relative to its closest positioned ancestor, if any; otherwise, it is placed relative to the initial containing block. Its final position is determined by the values of top, right, bottom, and left.

MDN - CSS - Position - Absolute

Add position:relative to pre so that the button can be absolutely positioned inside the pre

pre[class*="language-"] button {
  position: absolute;
  top: 5px;
  right: 5px;
  font-size: 0.9rem;
  padding: 0.15rem;
  border: ridge 1px #7b7b7c;
  border-radius: 5px;
  text-shadow: #c4c4c4 0 0 2px;
}

code[class*="language-"] button:hover {
  cursor: pointer;
  background-color: #bcbabb;
}

pre {
  position: relative;
}
<pre >
  <code >
    some code
  </code>
  <button>Copy</button>
</pre>

  • Related