CSS 在右侧放置一个 div 容器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5222523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 23:53:34  来源:igfitidea点击:

Position a div container on the right side

css

提问by Upvote

I want to develop some kind of utility bar. I can position each element in this bar side by side using float:left;

我想开发某种实用程序栏。我可以使用并排放置此栏中的每个元素float:left;

But I want the second element to be positioned at the very right of the bar. This is hard for me because the width of the bar is not static.

但我希望第二个元素位于栏的最右侧。这对我来说很难,因为栏的宽度不是静态的。

Have a look at my demo: http://jsfiddle.net/x5vyC/2/

看看我的演示:http: //jsfiddle.net/x5vyC/2/

It should look like this:

它应该是这样的:

enter image description here

在此处输入图片说明

Any idea how to achieve this using css?

知道如何使用 css 实现这一点吗?

回答by JohnP

Is this what you wanted? - http://jsfiddle.net/jomanlk/x5vyC/3/

这是你想要的吗?- http://jsfiddle.net/jomanlk/x5vyC/3/

Floats on both sides now

现在两边浮动

#wrapper{
    background:red;
    overflow:auto;
}

#c1{
   float:left;
   background:blue;
}

#c2{
    background:green;
    float:right;
}?

<div id="wrapper">
    <div id="c1">con1</div>
    <div id="c2">con2</div>
</div>?

回答by thirtydot

  • Use float: rightto.. float the second column to the.. right.
  • Use overflow: hiddento clear the floats so that the background color I just put in will be visible.
  • 使用float: right到..浮动第二列到..权利。
  • 使用overflow: hidden清除浮动,这样的背景颜色我只是把将是可见的。

Live Demo

现场演示

#wrapper{
    background:#000;
    overflow: hidden
}
#c1 {
   float:left;
   background:red;
}
#c2 {
    background:green;
    float: right
}

回答by anson

if you don't want to use float

如果你不想使用浮动

<div style="text-align:right; margin:0px auto 0px auto;">
<p> Hello </p>
</div>
  <div style="">
<p> Hello </p>
</div>

回答by Grms

Just wanna update this for beginners now you should definitly use flexbox to do that, it's more appropriate and work for responsive try this : http://jsfiddle.net/x5vyC/3957/

只是想为初学者更新这个,现在你应该明确地使用 flexbox 来做到这一点,它更合适并且适用于响应式尝试:http: //jsfiddle.net/x5vyC/3957/

#wrapper{
  display:flex;
  justify-content:space-between;
  background:red;
}


#c1{
   background:blue;
}


#c2{
    background:green;
}

<div id="wrapper">
    <div id="c1">con1</div>
    <div id="c2">con2</div>
</div>?

回答by Jonny Mousley

This works for me.

这对我有用。

<div style="position: relative;width:100%;">
    <div style="position:absolute;left:0px;background-color:red;width:25%;height:100px;">
      This will be on the left
    </div>

    <div style="position:absolute;right:0px;background-color:blue;width:25%;height:100px;">
      This will be on the right
    </div>
</div>