【发布时间】:2015-09-17 01:29:26
【问题描述】:
在下面的代码中,我希望满足以下条件:
- 粉红色的 div 始终跨越视口。
- 粉红色 div 的文本始终在视口中居中。
- 当屏幕“足够宽”时,蓝色 div 会向右浮动。
- 当屏幕“不够宽”时,蓝色 div 会堆叠在粉色 div 下方。
- 蓝色 div 跨越视口,堆叠时其文本居中。
- 解决方案应该是纯 CSS。
这是我目前的通行证:
<!DOCTYPE html>
<html>
<head>
<style>
#parent {
position: relative;
background-color: white;
width: 100%;
height: 20px;
}
#center {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
margin: auto;
background-color: pink;
text-align: center;
}
#placeholder {
position: relative;
height: 20px;
width: 500px;
}
#right {
position: relative;
float: right;
background-color: blue;
}
</style>
</head>
<body>
<div id="parent">
<div id="center">This text should always be centered in the VIEWPORT</div>
<div id="right">this text should float to the right</div>
<div id="placeholder"></div>
</div>
</body>
</html>
这是当前屏幕宽时的样子(正确):
这是屏幕窄时的样子(不正确):
这是窄屏时的样子:
【问题讨论】:
-
使用媒体查询根据屏幕大小调整css w3schools.com/cssref/css3_pr_mediaquery.asp
-
我确实知道这种可能性。在您看来,这是目前处理此类布局问题的标准方法吗?