Rocky
Rocky

Reputation: 47

Centering Images With CSS (Without Display: Block)

img.imgdemo {
  background: white;
  width: 65%;
  margin: auto;
}
<a class=imagelink href=periodictable.htm>
  <img class=imgdemo src=ptabledemo.png>
</a>

I'm trying to center an image that also acts as a link, but when it has a style of display: block, it acts as a block element, making everything in it's width a link as well. Is there any way to fix this?

Upvotes: 1

Views: 2040

Answers (3)

Andros Fenollosa
Andros Fenollosa

Reputation: 11

If your image is 200px

img {
  width: 200px;
  margin-left: calc(50% - 200px / 2);
}

If your image is 65%

img {
  width: 65%;
  margin-left: calc(50% - 65% / 2);
}

Upvotes: 1

Rob
Rob

Reputation: 15160

Images are inline just like text so:

.imagelink {
    text-align:center;
}

Upvotes: 4

Derek Story
Derek Story

Reputation: 9583

One option you could use is the transform: translate() property and give the a.imagelink display: inline-block. This will let you set the size of the image to whatever you want and make sure the link is the same size and stays centered at all times:

JS Fiddle

a.imagelink {
  display: inline-block;
  background: blue;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
}
img {
  width: 50%;
  display: block;
}

Upvotes: 2

Related Questions