在下面的代码中,我希望满足以下条件:
- 粉红色的 div 始终跨越视口(viewport)。
- 粉红色 div 的文本始终在视口(viewport)中居中。
- 当屏幕“足够宽”时,蓝色 div 会向右浮动。
- 当屏幕不够“宽”时,蓝色 div 堆叠在粉色 div 下方。
- 蓝色 div 横跨视口(viewport),其文本在堆叠时居中。
- 解决方案应该是纯 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>
这是当前屏幕较宽时的样子(正确):
这是窄屏幕时的样子(不正确):
这是窄屏幕时的样子:
最佳答案
您正在寻找这样的东西吗? https://jsfiddle.net/DIRTY_SMITH/v7k4oky8/4/
为适当的文本对齐编辑 fiddle
body{margin: 0;}
#parent {
position: relative;
background-color: white;
width: 100%;
height: 20px;
}
#center {
float: left;
margin: auto;
width: calc(100% - 500px);
background-color: pink;
padding-left: 250px;
}
#right {
float: left;
background-color: blue;
width: 250px;
}
@media (max-width: 610px){
#right {width: 100%; text-align: center;}
#center {width: 100%;}
}
关于html - 屏幕宽时向右浮动一个div,屏幕窄时堆叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32612964/