【问题标题】:how to make div float center of viewport always using CSS如何始终使用 CSS 使 div 浮动视口中心
【发布时间】:2018-01-23 00:58:27
【问题描述】:
目标是让包含两个图像的 div(在本例中为 willscape-holder)始终浮动在视口的中间。有没有办法做到这一点,而不必为每种类型的屏幕调整顶部和底部边距的媒体查询?提前感谢您的帮助。
body {
background: url(../images/willscape-bg.png);
background-repeat: no-repeat;
background-size: 100% 100%;
/* background-position: center top; */
background-attachment: fixed;
}
.container {
height: 100vh;
}
.willscape-holder {
width: 100%;
max-width: 350px;
margin: 0 auto;
padding: 0 20px;
}
#willscape-logo {
padding: 0 60px;
width: 100%;
}
#willscape-title {
width: 100%;
max-width: 500px;
}
<body>
<div class="container">
<div class="willscape-holder">
<a href="" target="_blank"><img class="img-responsive" id="willscape-logo" src="assets/images/willscape-logo.png" /></a>
<a href="" target="_blank"><img class="img-responsive" id="willscape-title" src="assets/images/willscape.png" /></a>
</div>
</div>
</body>
【问题讨论】:
标签:
html
css
twitter-bootstrap
media-queries
【解决方案2】:
你可以使用 display:table/table-cell;属性
https://www.w3.org/TR/CSS2/tables.html
17.2 CSS 表格模型
CSS 表格模型基于 HTML4 表格模型,其中表格的结构与表格的视觉布局非常相似。在此模型中,表格由可选标题和任意数量的单元格行组成。表模型被称为“行主要”,因为作者在文档语言中明确指定行,而不是列。一旦指定了所有行,就会派生列——每行的第一个单元格属于第一列,第二个单元格属于第二列,等等)。行和列可以在结构上进行分组,并且这种分组反映在表示中(例如,可以在一组行周围绘制边框)。
因此,表格模型由表格、标题、行、行组(包括页眉组和页脚组)、列、列组和单元格组成。
/* update*/
html {
height:100%;/* equals min-height */
width:100%;
table-layout:fixed ; /*if fixed, then width is width not min-width */
display:table;
}
body {
display:table-cell;
vertical-align:middle;
/* end update */
background: url(../images/willscape-bg.png);
background-repeat: no-repeat;
background-size: 100% 100%;
/* background-position: center top; */
background-attachment: fixed;
}
.container {
/* height: 100vh;*/
}
.willscape-holder {
width: 100%;
max-width: 350px;
margin: 0 auto;
padding: 0 20px;
}
#willscape-logo {
padding: 0 60px;
width: 100%;
}
#willscape-title {
width: 100%;
max-width: 500px;
}
<body>
<div class="container">
<div class="willscape-holder">
<a href="" target="_blank"><img class="img-responsive" id="willscape-logo" src="assets/images/willscape-logo.png" /></a>
<a href="" target="_blank"><img class="img-responsive" id="willscape-title" src="assets/images/willscape.png" /></a>
</div>
</div>
</body>
【解决方案3】:
.centered {
position: fixed;
top: 50%;
left: 50%;
/* don't forget to add prefixes */
transform: translate(-50%, -50%);
}
不需要其他任何东西,无论元素或 ViewPort 的大小如何,都将始终居中。
为了更好地理解Centering with CSS