html - 垂直和水平居中图像

标签 html css alignment

我通常使用 div 上方的内容将所有内容向下推。这个元素需要一个水平和垂直居中的单一图像,没有别的。

我的搜索出现了很多结果,但我进行了混合和匹配,但无济于事。想帮忙吗?

这是简单的 HTML

<div id="entpa">
    <section id="mainContAPos">
    </section>
</div>

这是我的 CSS

body{
  background-color: #0D0D0D;
}

#entpa{
  position: absolute;
}

#mainContAPos{
  position: fixed;
  vertical-align: middle;
  background-image: url('frontpage1366.png');
  width: 1366px;
  height: 768px;
  border: 8px solid #FFF4CF;
  border-radius: 16px;
}

最佳答案

试试这个:

HTML(无变化)

 <div id="entpa">
    <section id="mainContAPos"></section>
 </div>

CSS

html, body { height: 100%; }

#entpa {
     display: flex;
     justify-content: center; /* center child div horizontally (in this case) */
     align-items: center; /* center child div vertically (in this case) */
     height: 100%;
     /* position: absolute; REMOVE; no need for this */
 }

 #mainContAPos{
     /* vertical-align: middle; REMOVE; no need for this */
     background-image: url('frontpage1366.png');
     width: 1366px;
     height: 768px;
     border: 8px solid #FFF4CF;
     border-radius: 16px;
  }

演示:http://jsfiddle.net/qxmLk1j6/

注意所有主流浏览器都支持 flexbox,except IE 8 & 9 .

有关 CSS Flexbox 的更多信息,请访问:

关于html - 垂直和水平居中图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32803967/

相关文章:

javascript - 如何为引导下拉框设置焦点

HTML/Body 没有封装整个高度

html - 如何在居中对齐容器内的左对齐 div 内居中对齐内容(例如图像)?

css - 使用 CSS 自定义我的 WordPress 网站无法可靠运行

c++ - sizeof 为我的结构提供了意想不到的结果

html - 将 div 左中右对齐与物化时的 block 行为

javascript - 将图像分配给随机 div?

html - 使用 css 相对和绝对包装图像

html - 在 <fieldset> 背景中应用不透明度时,如何删除 <legend> 标签中的不透明度?

css - 分离背景颜色和不透明度?