CSS,想将一个项目与居中的div的左侧对齐,并在其周围留一些间距吗?

时间:2019-03-06 01:20:15

标签: html css center

我有一个容器div,其中有两个子div:

<div id="container">

    <div id="child1">
    I want this to be displayed next to the child2 div, 
    but offset to the right by about 3em. Basically, 
    I want spacing between it and the second child, 
    but I want the second child to remain centered.
    </div>

    <div id="child2">
    I want this to be centered on the page
    </div>

</div>

我试图弄清楚如何在第二个孩子和第一个孩子div之间增加一些间距的同时使第二个孩子在页面上水平居中。有谁知道如何做到这一点?我正在使用以下CSS,但无法在第二个div和第一个div之间添加填充。

我有以下CSS,但无法完全正常工作:

#container {
    margin: auto;
    text-align: center;
}
#child1, #child2 {
    display: inline-flex;
    float: left;
}

2 个答案:

答案 0 :(得分:0)

#container {
    margin: auto;
    text-align: center;    
}

#container #child1{
  border: 5px solid red;  
  margin-right:30%;
/*margin-right:50%;*/
}


#container #child2{
  border: 5px solid green;  
  margin-left:30%;
  margin-right:30%;
}
<div id="container">

    <div id="child1">
    <p>I want this to be displayed next to the child2 div, 
    but offset to the right by about 3em. Basically, 
    I want spacing between it and the second child, 
    but I want the second child to remain centered.</p>
    </div>
<br>
<br>
    <div id="child2">
      <p>I want this to be centered on the page</p>
    </div>

</div>
嘿杰森, 希望你一切都好。

您可以控制div的边距,将居中位置将左右两侧都设置为30%,将潜水位置设置在屏幕左侧,则可以在右边添加30%的边距,因此它会将其从屏幕右侧推开30%,如果您希望它离屏幕右侧更远且最靠近左侧,则可以增加到50%。

enter image description here

enter image description here

答案 1 :(得分:0)

使用flex怎么样? 我不知道我是否明白你的意思。但是flex是布局的好工具。 这里有一个很好的flex指南:https://scotch.io/tutorials/a-visual-guide-to-css3-flexbox-properties

#container {
    margin: auto;
    display:flex;
    flex-direction:column;
}
#child1{
  padding-right:3em;
}
#child2 {
  padding-top:3em;
  align-self: center;
}
<div id="container">
    <div id="child1">
    I want this to be displayed next to the child2 div, 
    but offset to the right by about 3em. Basically, 
    I want spacing between it and the second child, 
    but I want the second child to remain centered.
    </div>
    <div id="child2">
    I want this to be centered on the page
    </div>
</div>