Html 在第三个容器 div 内水平对齐 2 个 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11764905/
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 02:00:52  来源:igfitidea点击:

align 2 divs horizontally inside a third container div

htmlcss

提问by cppit

I have the following code:

我有以下代码:

<div id="container">
    <div id="div1">Div 1</div>
    <div id="div2">Div 2</div>
</div>

I want to be able to have #box1 and #box2 one next to the other inside the container. Container is centered

我希望能够在容器内将#box1 和#box2 放在另一个旁边。容器居中

回答by Alex W

This will center the container, and have the two divs within it centered, while separating the styles from the actual content:

这将使容器居中,并使其中的两个 div 居中,同时将样式与实际内容分开:

HTML:

HTML:

<div id="container">
    <div>Div 1</div>
    <div>Div 2</div>
</div>

CSS:

CSS:

#container > div
{
    display: inline-block;
    border: solid 1px #000;
}
#container
{
    border: solid 1px #ff0000;
    text-align: center;
    margin: 0px auto;
    width: 40%;
}   

Working example:

工作示例:

http://jsfiddle.net/JLjjK/

http://jsfiddle.net/JLjjK/

2017 Update:

2017 更新

Flexbox is becoming much more commonplace. Here's a way to achieve similar results with Flexbox:

Flexbox 正变得越来越普遍。下面是一种使用 Flexbox 实现类似结果的方法:

HTML:

HTML:

<div class="outer">
  <div>1</div>
  <div>2</div>
</div>

CSS:

CSS:

.outer {
  border: 1px solid #000;
  display:flex;
  justify-content: center;
  padding: 3px;
}
.outer > div {
  border: 1px solid #000;
  margin:2px;
}

Example: https://jsfiddle.net/pb61a1cj/1/

示例:https: //jsfiddle.net/pb61a1cj/1/

回答by JAB

Try this:

尝试这个:

HTML:

HTML:

<div id="container">
    <div id="box1" class="inlined">
        <div id="box3"></div>
        <div id="box4"></div>
    </div>
    <div id="box2" class="inlined"></div>
</div>

CSS:

CSS:

.inlined
{
    display: inline-block;
}

You could also use .inlined { float: left; }or .inlined { float: right; }, but those can have unexpected behavior depending on the surrounding elements.

您也可以使用.inlined { float: left; }.inlined { float: right; },但根据周围的元素,这些可能会产生意外的行为。

回答by 150GritSandpaper

I hope this is what you are looking for...

我希望这就是你正在寻找的......

<style type="text/css">
.container{
    margin-left: auto;
    margin-right: auto;
    width: 300px;
}
.box1, .box2 {
    width:280px;
    height:auto;
    float:left;
    margin-bottom:10px;
    padding:10px;
    border:1px solid #888;
}
.box1 {
    clear:left;
    margin-right:10px;
}
.clear {
    clear:both;
}
</style>



<div id="container">
    <div class="box1">
       Enter box 1 content here.
    </div>
    <div class="box2">
       Enter box 2 content here.
    </div>
    <div class="clear"></div>
</div>