- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在制作一个带有正文背景的布局。我需要将它水平和垂直居中。为此,我使用 background-position:center。
background-image:url('address');
background-repeat:no-repeat;
background-position:50% 50%;
但是,背景没有正确垂直定位:您只能在屏幕顶部看到一半的图像。在这里查看 link to codepen .
作为解决方案,我尝试使用具有不同尺寸和背景位置的图像:50% 50%。然后我仔细检查了其他背景相关选择器,发现如果我添加背景附件并将其从滚动到固定的默认值更改,则图像会正确居中。
谁能解释一下为什么会这样?
最佳答案
如果您没有为 body
指定高度,就会发生这种情况,因为它的默认值为 0。
body
的高度基于其内容,背景图像不会设置它。
这是一个示例,展示了您需要如何做
html, body {
margin: 0;
height: 100%;
}
body {
background-image: url(http://placehold.it/200);
background-repeat: no-repeat;
background-position: center center;
}
有时,当需要给 body
一个高度,而定位的 div
是一种选择时,它可能会产生其他问题
#bkgdiv {
position: absolute;
left: 0; top: 0; right: 0; height: 100vh;
background-image: url(http://placehold.it/200);
background-repeat: no-repeat;
background-position: center center;
}
<div id="bkgdiv"></div>
因此,根据您如何/是否需要使用 background-attachment: scroll
和/或定位 div
,这里有一个示例显示了它们在一个时的行为滚动(和一个 fiddle demo 一起玩)
html, body {
margin: 0;
height: 100%;
}
body {
background-image: url(http://placehold.it/200);
background-repeat: no-repeat;
background-position: center center;
background-attachment: scroll;
}
#bkgdiv {
position: absolute;
left: 0; top: 0; right: 0; height: 100vh;
background-image: url(http://placehold.it/180/0f0);
background-repeat: no-repeat;
background-position: center center;
}
#bkgdivfixed {
position: fixed;
left: 0; top: 0; right: 0; height: 100vh;
background-image: url(http://placehold.it/160/ff0);
background-repeat: no-repeat;
background-position: center center;
}
<div id="bkgdiv"></div>
<div id="bkgdivfixed"></div>
<div style="width: 5px; height: 150vh; background: red; margin: 5px"></div>
关于css - "background-positon:center"不适用于 "background-attachement:scroll",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39681251/
这看起来很简单,但却难倒了我。 我正在尝试获取使用 Bootstrap 3 的列偏移定位的 div 的左侧位置。 我用 positon.left 得到 15px ... Bootstrap 装订线。
我有两个重叠的全宽对象(菜单和搜索+登录表单)每次我想更改 z-index 时,只有其中一个可以正常工作(可点击/具有工作链接)。我不能将它们包含在一起,因为那样看起来不太好。我正在尝试使其中一个固定
我正在制作一个带有正文背景的布局。我需要将它水平和垂直居中。为此,我使用 background-position:center。 background-image:url('address');
我是一名优秀的程序员,十分优秀!