How to make one element stay on top of another with :after?

Asked

Viewed 3,738 times

2

Using the pseudoelement :after, I created an image caption. How can I make the caption on top of the image and not on the bottom?

.estrutura{
  width:10%;
  height:30%;
  }

.estrutura:after{
  position: fixed;	
  content:"Estrutura";
  width:20%;
  height:20px;
  background-color: blue;
}
<div class="estrutura">
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a2/Biandintz_eta_zaldiak_-_modified2.jpg/550px-Biandintz_eta_zaldiak_-_modified2.jpg">
</div>

  • The top you mean, would be before or about? if it’s before you can use the :before thus the content is placed before the image

  • On top of the image. At the bottom of it. At the bottom.

  • tried to use the z-index?

  • Run the Snippet and open in full screen to see the created element

2 answers

1

This should solve your problem. The position of .estrutura:after this as relative, and added the top: -32px to move the text up and above the image.

.estrutura{
  width:10%;
  height:30%;
  }

.estrutura:after{
  position: relative;	
  content:"Estrutura";
  width:20%;
  height:20px;
  top: -32px;
  background-color: blue;
}
<div class="estrutura">
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a2/Biandintz_eta_zaldiak_-_modified2.jpg/550px-Biandintz_eta_zaldiak_-_modified2.jpg">
</div>

0

When using position: fixed;, the element will position itself relative to the document (whole window) and not to the parent element.

You must set position: relative; at the parent element so that the pseudo-element :after be positioned inside it. Next with the styles top and left you position it where you wish on the parent element:

.estrutura{
  width:10%;
  height:30%;
  position: relative;
  }

.estrutura:after{
  position: absolute;	
  content:"Estrutura";
  width:20%;
  height:20px;
  background-color: blue;
  bottom: 0;
  left: 0;
}
<div class="estrutura">
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a2/Biandintz_eta_zaldiak_-_modified2.jpg/550px-Biandintz_eta_zaldiak_-_modified2.jpg">
</div>

Note that as you are restricting the dimensions of parent element .estrutura smaller than the image itself, the size of the :after will be based on that size too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.