在下面的代码中,我希望保留以下条件:
这是我目前的通行证:
<!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>
这是屏幕宽度(正确)时的当前状态:
这是屏幕很窄(不正确)时的样子:
这是屏幕狭窄时应该是什么样子:
答案 0 :(得分:2)
编辑小提琴以进行正确的文字对齐
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%;}
}
答案 1 :(得分:-1)
这是我的解决方案。我不知道这是否是最好的。首先,它需要您设置明确的高度。根据我在某处阅读的最佳实践,我为移动设置了默认值,并为大屏幕设置了更改。我注意到如果你把它放在JSFiddle中它不能正常工作,但如果你在浏览器中使用它(只测试了Firefox)就会这样做。
<!DOCTYPE html>
<html>
<head>
<style>
body{margin: 0;}
#parent {
position: relative;
width: 100%;
height: 40px;
text-align:center;
}
#center {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
margin: auto;
background-color: pink;
}
#right {
position: absolute;
top: 20px;
bottom: 0;
right: 0;
left: 0;
margin: auto;
background-color: #00FFFF;
}
@media only screen and (min-width: 480px) {
#parent {
height: 20px;
}
#right {
position: relative;
float: right;
top: 0;
}
}
</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>
</body>
</html>