Html css图片定位中心

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21153161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 00:31:17  来源:igfitidea点击:

css image positioning center

htmlcsscss-position

提问by Faytraneozter

i have problem with positioning image

我有定位图像的问题

<div class="foto img-thumbnail">
  <img class="img-thumbnail tengah" src="member/37/foto_profile/profile37.png">
</div>

the css file

css文件

.foto {
background-image: url('member/37/foto_profile/large.jpeg');
height: 300px;
background-repeat: no-repeat;
background-size:cover;
background-position: 
center center;
width: 100%;
}
.tengah {
position: absolute;
}

preview

预览

GREEN= classtengah

GREEN=登加

RED= classfoto

红色=课堂照片

i want the image (RED) positioning center of div

我想要div的图像(红色)定位中心

when i change css like

当我改变 css 时

.tengah {
left: 50%;
top: 50%;
position: absolute;
}

it returning the center of image preview1

它返回图像的中心 预览1

anybody can help me?

有人可以帮助我吗?

thanks before :)

之前谢谢:)

回答by davidpauljunior

I think you're talking about centering the .tengahdiv in the .foto.

我认为您是在谈论将.tengahdiv 集中在.foto.

If so, then you need:

如果是这样,那么您需要:

.foto {
  background-image: url('member/37/foto_profile/large.jpeg');
  height: 300px;
  background-repeat: no-repeat;
  background-size:cover;
  background-position: 
  center center;
  width: 100%;
  position: relative; /* ADDED */
}

.tengah {
  left: 50%;
  top: 50%;
  position: absolute;
  margin-top: -30px; /* ADDED */
  margin-left: -30px; /* ADDED */
}

The margins are half the width and height of the <div>you want centered.

边距是<div>您想要居中的宽度和高度的一半。

回答by Martin Sansone - MiOEE

A cleaner method that will adapt to different size screens would be to avoid the "position:absolute" altogether by setting auto margins left and right for the .tengah class:

一种适应不同尺寸屏幕的更简洁的方法是通过为 .tengah 类设置左右自动边距来完全避免“位置:绝对”:

.tengah {
   position: relative;
   margin-left: auto;
   margin-right: auto;
   top: 50%;
}

This style class will auto center the image/div. The "top" can be adjusted a little depending on the image length if "vertical-align" is not used.

这个样式类将自动居中图像/div。如果不使用“垂直对齐”,可以根据图像长度稍微调整“顶部”。