Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css: how to position a X sign at the top right corner of the img element

Besides, position: relative, and then set right and bottom position?

I wanna the close sign positioned top right corner whatever the size of the img

like image 499
9blue Avatar asked Mar 20 '14 19:03

9blue


People also ask

How do I put something in the top right corner in CSS?

Try using float: right; and a new div for the top so that the image will stay on top.

How do I align text to the top right corner in CSS?

Aligning text in CSS can be achieved using the text-align property or the vertical-align property. The values are: left. right.

How do you put a div in the top right corner?

you can play with the top and right properties. If you want to float the div even when you scroll down, just change position:absolute; to position:fixed; . Hope it helps. Save this answer.


2 Answers

You can use absolute position on the X sign and set its position with respect to the relatively positioned parent.

document.querySelector('.close').addEventListener('click', function() {
  console.log('close');
});
.wrapper {
  position: relative;
  display: inline-block;
}
.close:before {
  content: '✕';
}
.close {
  position: absolute;
  top: 0;
  right: 0;
  cursor: pointer;
}
<div class="wrapper">
  <img src="https://www.google.com/images/srpr/logo11w.png" />
  <span class="close"></span>
</div>
like image 111
Oriol Avatar answered Oct 26 '22 23:10

Oriol


Wrap the <img> in another element with position: relative and place the X sign as a sibling to the image. Then give the X sign position: absolute and top and right values of 0 or whatever.

You'll also need to make sure the image is either width: 100% and/or the wrapping element is floated or has display: inline-block.

Example markup:

<div class="parent">
  <img src="image.jpg">
  <button class="close">X</button>
</div>

Example CSS:

.parent {
  position: relative;
  display: inline-block;
}

.close {
  position: absolute;
  top: 0;
  right: 0;
}

Here's a pen of this: http://codepen.io/Mest/pen/FjeuD/

like image 32
Nils Kaspersson Avatar answered Oct 26 '22 23:10

Nils Kaspersson