Skip to content Skip to sidebar Skip to footer

Position Text Over Image On Hover Using Html/css

After looking at existing answers, as well as other online tutorials, I still can't figure out how to position text over an image upon hover. Here is an example of what the image w

Solution 1:

The key is not to position the element 'on hover' - but to positiion it how you want it, and display it - on hover / either with JavaScript - or opacity and CSS etc.

https://jsfiddle.net/sheriffderek/grkaw0o3/

markup

<divclass="parent"><divclass="child"><span>stuff</span></div></div>

styles

.parent {
  position: relative; /* define context for absolutly positioned children */width: 200px;
  height: 200px;
  background: red;
}

.child {
  position: absolute; /* position based on boundery created by nearest relative ancestor */top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: white;
}

Now with hover... (same markup)

https://jsfiddle.net/sheriffderek/ykpacq59/

.parent {
  position: relative; /* define context for absolutly positioned children */width: 200px;
  height: 200px;
  background: red;
}

.parent:after {
  content: ''; /* :after has to have a content... but you don't want one */position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100%;

  background: rgba(0,0,0,0);

  transition: 1s;
}

.parent:hover:after {
  background: rgba(0,0,0,.5); 
}

.parent:hover.child {
  opacity: 1;
}

.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

  z-index: 5; /* only works when position is defined *//* think of a stack of paper... this element is now 5 higher than the bottom */color: white;

  opacity: 0;
  transition: .5s;
}

Solution 2:

You can use z-index.

Add position relative to parent and then create divs for image and text with position absolute and set the higher z-index to the top (text) div

Solution 3:

You can use the sibling selector to target your text element (i would also wrap the p and h4 into a block level element.

I don't think css can move up nodes on hover.

Is there a CSS parent selector?

.projectimg:hover ~ p, .projectimg:hover ~ h4 {
    opacity: 1;
}

Post a Comment for "Position Text Over Image On Hover Using Html/css"