Centering content in a flex box with a background using '
Centering content in a flex box with a background using 'background-size: contain'
首先,这里有一个Fiddle的例子。
我要做的是将内容(即h1
和h2
)与缩放到当前背景图像大小的伸缩框对齐。根据我自己的尝试,我假设这将不得不是一个JavaScript解决方案(例如,我将不得不计算背景图像缩放后的大小),但我当然欢迎任何类型的解决方案。
我想问这个问题最简洁的方式是:如何使用background-size: contain
在元素上居中内容?
我还有其他一般性问题:
- 什么是最好的方法来计算一个背景图像的尺寸,不管它使用什么
background-size
属性? - 对于这个特定的场景,除了伸缩盒之外,还有什么能更好地集中内容吗?当使用
cover
时,很容易将东西居中,但这似乎是一个全新的游戏。 - 是否有可能使弹性容器(由红色边框表示)与纯CSS的背景图像的大小和约束相匹配?请注意,我最终希望这是响应性的,我不一定要寻找定义静态高度。
我不清楚你真正想要达到的目标,但我怀疑你只是错过了:
background-position:50% 50%;
检查:http://jsfiddle.net/farc8h1d/
- 的回答是"原则上没有这种方法"。
-
<center>
仍然不能完全复制。 - 仅通过CSS定义宽度/高度比率,例如,这样的:http://www.mademyday.de/css-height-equals-width-with-pure-css.html
基本思想:使用<img>
和width:100% ; height:auto;
来定义其容器的大小。文本使用绝对位置嵌入该容器。
这个提琴实际上是我正在寻找的行为。这篇文章提供了JavaScript。
然而,它似乎只在Chrome正常工作;而不是火狐或ie浏览器。我正在调查,但这应该能更好地让我了解我在做什么。
代码:
var img = new Image();
var elem = document.getElementsByClassName("section-1")[0];
img.src = window.getComputedStyle(elem, null).getPropertyValue("background-image").replace(/url'(|')$/ig, "");
function resize() {
var bgHeight = elem.offsetWidth * img.height / img.width;
elem.style.height = bgHeight + 'px';
}
window.onresize = resize;
resize();
相关文章:
- 如何通过引用var Using DataTables来进行分页或排序
- 从Chrome扩展名中的popup.html文件在background.js文件中运行一个函数
- Object.prototype using 'this'
- using LocalStorage ionic 2
- jQuery Replacing, Using arrays
- Using jQuery with classes from ES6
- Dropdownlist using javascript
- Tic-Tac-Toe using React JS
- 在jqueryui中更改关键字using
- Using php mktime()
- Twitter api using Javascript
- Bootstrap-Datepicker not selecting date when using "set
- 如何使主体采用等同于 style=“background-color: returnBlue()” 的样式属性,其中 r
- fetch data from db using javascript & php
- Javascript style.background在IE中不起作用
- Using closures in node js
- googleTagManager using JQueryMobile
- Javascript Object - using jQuery and this
- Googlemaps Javascript API KML layer - Using Open charge map
- Centering content in a flex box with a background using '