html - 屏幕宽时向右浮动一个div,屏幕窄时堆叠

标签 html css

在下面的代码中,我希望满足以下条件:

  1. 粉红色的 div 始终跨越视口(viewport)。
  2. 粉红色 div 的文本始终在视口(viewport)中居中。
  3. 当屏幕“足够宽”时,蓝色 div 会向右浮动。
  4. 当屏幕不够“宽”时,蓝色 div 堆叠在粉色 div 下方。
  5. 蓝色 div 横跨视口(viewport),其文本在堆叠时居中。
  6. 解决方案应该是纯 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>

这是当前屏幕较宽时的样子(正确):

wide

这是窄屏幕时的样子(不正确):

narrow

这是窄屏幕时的样子:

narrow goal

最佳答案

您正在寻找这样的东西吗? 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/

相关文章:

javascript - 仅使用 JavaScript 的递归 HTML 表格树

css - 在不丢失滚动条的情况下缩放容器以监视大小?

html - 伪元素中的 CSS 指针事件在 Firefox 中不起作用

javascript - 嵌入式dll资源

html - 如何为mp3文件设置下载属性?

html - 使用 nth-child 只显示第一个,第二个和最后一个 child ?

html - 如何用输入和按钮创建三 Angular 形的形式?

css - 为什么 IE 7 中的 div 显示与其他浏览器不同?

html - 已经居中的 div 中的中心框

html - 即使内容不同,如何让我的 div 空间保存