在同一行和中心上的两个Div对齐它们 [英] Two Divs on the same row and center align both of them

查看:172
本文介绍了在同一行和中心上的两个Div对齐它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个这样的div

I have two divs like this

<div style="border:1px solid #000; float:left">Div 1</div>
<div style="border:1px solid red; float:left">Div 2</div>



我希望它们显示在同一行,所以我使用 float: left

我想让他们都在页面的中心,所以我试着用另一个div包装这样

I want both of them to be at center of the page as well, so I tried to wrap them with another div like this

<div style="width:100%; margin:0px auto;">
  <div style="border:1px solid #000; float:left">Div 1</div>
  <div style="border:1px solid red; float:left">Div 2</div>
</div>

但它不工作。如果我将代码更改为

But it doesn't work. If I change the code to this

<div style="width:100%; margin-left:50%; margin-right:50%">
  <div style="border:1px solid #000; float:left">Div 1</div>
  <div style="border:1px solid red; float:left">Div 2</div>
</div>

然后它会到中心,但水平滚动条是在那里,它似乎不是真正居中

then it's going to the center, but the horizontal scrollbar is there and it seems like it's not really centered as well.

你能请我向我建议如何实现这一点?谢谢。

Can you please kindly suggest to me how can I achieve this? Thanks.

编辑:我想要内部div(Div 1和Div 2)也是中心对齐。

I want the inner div (Div 1 and Div 2) to be center align as well.

推荐答案

您可以这样做

<div style="text-align:center;">
    <div style="border:1px solid #000; display:inline-block;">Div 1</div>
    <div style="border:1px solid red; display:inline-block;">Div 2</div>
</div>  

http: //jsfiddle.net/jasongennaro/MZrym/


  1. 将其封装在 div text-align:center;

  2. 给予 div sa display:inline-block; 而不是 float

  1. wrap it in a div with text-align:center;
  2. give the innder divs a display:inline-block; instead of a float

最好将css放在样式表中。

Best also to put that css in a stylesheet.

这篇关于在同一行和中心上的两个Div对齐它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆