1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

borderで囲んだ画像のぼやけをCSSで解消する方法

Last updated at Posted at 2022-01-25

ぼやけた条件

  • 140px × 140pxの枠
  • border-width 2px
  • 2倍の画像「280px × 280px」の画像を使用
  • 画像は2倍じゃなくてもぼやける

原因

borderが2pxあるので、画像表示領域が4px分小さくなっているため
border_in_img.png
※じゃあ136 ×136の画像を用意すればいいんじゃないの?っていう話ですが…
 まー、そうはいかない状況があったりなんかして…
 CSSでなんとかしたいと思った話です。

解決方法

<div class="img_wrapper">
	<img src="画像のパス" alt="">
</div>
.img_wrapper {
  width: 140px;
  height: 140px;
  border: 2px solid #333;
  overflow: hidden;
  position: relative;
}
.img_wrapper > img {
  width: 140px;
  position: absolute;
  top: -2px; /* borderが2pxのため */
  left: -2px; /* borderが2pxのため */
}

画像にposition: absolute;を使用しているのは、画像を中央に配置するためです。

〜 2022年2月2日修正、追記 〜

上記のよりももっと簡単な方法がありましたので修正します…すみません…
borderではなくoutlineを使えば大丈夫でした:pray:

<div class="img_wrapper">
	<img src="画像のパス" alt="">
</div>
.img_wrapper {
  width: 140px;
  outline: 2px solid #333; 
}
.img_wrapper > img {
  width: 100%;
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?