css - 如何在固定位置的情况下将图像设置在中心

标签 css

<分区>

我正在尝试将图像居中并在 CSS 中固定位置。我试过的代码

<style>
.bgimg {
    top: 50%;
    left: 50%;
    position: fixed;
    opacity:0.09;
    marging: auto;
}
</style>

引用https://www.w3schools.com/code/tryit.asp?filename=FJZQPD9BZUBG

最佳答案

对于可变宽度/高度的内容,您需要使用带有转换的百分比偏移,如下所示:

.bgimg {
  top: 50%;
  left: 50%;
  position: fixed;
  opacity:0.09;
  transform: translate(-50%, -50%);
}

或者,如果您知道宽度和高度,则可以避免使用转换并将所有位置设置为 0 并与 margin: auto; 配对:

.bgimg {
  width: 400px;
  height: 400px;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
}

您可以在下面看到这两种方法的实际效果!

.bgimg {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  opacity: .5;
}

/* you need to set the width and height on this one, otherwise it stretches it to fill */
.center-something-without-transform {
  width: 50px;
  height: 50px;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  background-color: blue;
}
<img class="bgimg" src="http://placekitten.com.s3.amazonaws.com/homepage-samples/200/287.jpg" />
<div class="centered-without-transform"></div>

关于css - 如何在固定位置的情况下将图像设置在中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46474228/

上一篇:javascript - 我的导航栏中有两个下拉菜单,如果一个打开,如果我打开另一个,它不会关闭

下一篇:html - 无法使用 css 样式提交按钮

相关文章:

html - 如何使登录表单不适合整个屏幕宽度

html - 如何解决在IE7中使用CSS3 Pie时元素上边距消失的问题

css - 厚 Div 边框顶部的关闭按钮

html - 在 Css 中删除图像的背景

html - 将页面旋转 90 度

html - 可变字体大小的文本垂直居中

javascript - 折叠/展开所有菜单项。 - HTML/JS/CSS/ Bootstrap 3

html - 如何在不换行的情况下在 Java Mail 中添加内联样式

php - 如何激活循环选项卡 PHP

javascript - 当克隆包含单选按钮的 div 时,jQuery 会自动向单选按钮名称添加 +1