如何在不影响标题内容的情况下将 div 浮动到标题 div 的右侧?

How do I float a div to the right of a title div without affecting the content of the title?

我想知道如何获得以下结果:

绿色是一个容器 div 700 像素宽。蓝色是一个标题区域,它填充了绿色容器 width-wise,中间有一些标题文本。红色需要在不影响标题文字流向的情况下向右浮动。

我该如何实现?我试过将红色框浮动在右侧,但由于某种原因它似乎将标题中的文本推到了左侧。

Edit - 郑重声明,我没有发布示例,因为 HTML 和 CSS 不是我的专业领域,我我正在努力回到文本未对齐的示例(尝试了我一直在阅读的六种不同方法)。

以下是我的大致尝试:http://jsfiddle.net/3fgytw0u/

<!DOCTYPE html>
<head>
    <title></title>
    <style>
    #Container {
    width: 700px ;
    margin-left: auto ;
    margin-right: auto ;
    }

    #Title {
    background-color: red;
    text-align: center;
    }

    #GameGuidelines{
        align:right;
    width: 200px;
    background-color: grey;
    }
    </style>

</head>
<body>

<div id="Container">

<div id="Title">
    <h1>This</h1>
    <h2>Is</h2>
    <h2>A</h2>
    <h2>Long</h2>
    <h2>Title Title Title Title</h2>
</div>

    <div id="GameGuidelines">
        <ul>
            <li>Some</li>
            <li>Info</li>
            <li>Here</li>
        </ul>
    </div>

<div id="Introduction">
    <p>Rest of the page continues here</p>
</div>

</div>

</body>
</html>

也许对您有帮助:Link

#Container {
width: 700px ;
margin-left: auto ;
margin-right: auto ;
position: relative;
}

#Title {
background-color: red;
text-align: center;
}

#GameGuidelines{
    text-align:right;
position: absolute;
right: 0;
top: 0;
width: 200px;
background-color: grey;
}

另一种定位方法可以使用负数 margin-left 等于红色区域的宽度:

h2 {
    padding: 10px;
    background: #EEE;
    text-align: center;
    overflow: hidden;
}
h2 .right-block {
    width: 50px;
    height: 50px;
    background: coral;
    float: right;
    margin-left: -50px;
}
<h2>
    Some centered text
    <div class="right-block"></div>
</h2>

这就是你想要的。

  <html>

<head></head>
<body>
    <div style="border:green 1px solid;height:700px;" >
        <div style="border:blue 1px solid;width:100%;height:200px;text-align:center">
            Some Title Text
            <div style="float:right;border:1px red solid;width:100px;height:100px;margin-right:5px;position:relative;">
                Some text
            </div>
        </div>
    </div>
</body>
</html>

红色div会漂浮在蓝色里面的右边。

这可以简单地通过将内部 div 定位为 position: absolute 并将其放置 right: 0px 来完成,但是因为您需要防止它不会开始与相反,主显示,您也将 position: relative 放在外部 div 。还要确保在编写时先放置红色 div,然后放置带有紫色文本的 div,或者您可以只添加 top: 0px,这样您就不再关心它了。

那么应该可以了! 这是 fiddle:http://jsfiddle.net/xg6rove7/

但请注意,红色框中的任何文本都可能与紫色框中的文本重叠,正如我在 fiddle 中试图向您展示的那样。您最好在两侧使用等于框宽度的填充,或者只使用普通的旧 float: right

将元素向上移动到 header,将其设置为 position:absolute 并给它一个 margin-left:500px;

http://jsfiddle.net/3fgytw0u/2/ <-- 那个是对的