【问题标题】:4 divs and need to center 2 center divs4 个 div,需要居中 2 个中心 div
【发布时间】:2014-10-03 23:31:17
【问题描述】:

我在这样的容器中有四个 div:

<div class="container">
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
</div>

我想让第一个和最后一个 div 与屏幕边缘对齐,并且只将两个 div 居中。我尝试显示内联块并调整边距,但我无法弄清楚。请尝试并启发我!

亲切的问候

【问题讨论】:

  • 给他们不同的classes 然后用css设置类的样式

标签: html css containers center inline


【解决方案1】:

使用这个 HTML

<div class="container">
    <div class="block left">1</div>
    <div class="block">2</div>
    <div class="block">3</div>
    <div class="block right">4</div>
</div>

然后是这个 CSS

.container {
    display:block;
    text-align:center
}
.block {
    display:inline-block;
    border:1px solid #000;
    padding:10px;
    margin:auto
}
.left {
    float:left
}
.right {
    float:right;
}

您也可以使用 first-child 和 last-child,但是将类添加到 first 和 last 更容易div

See fiddle here

【讨论】:

  • 容器应该包含一个清除修复以确保它包含浮动元素。
【解决方案2】:

尝试使用 :nth-of-type() 伪类允许您使用公式选择元素,例如:http://jsfiddle.net/csdtesting/11fh7suy/

//second div    
div.container div:nth-of-type(2) {
        background-color: #9999ff;
        text-align:center;
    }
//third div
    div.container div:nth-of-type(3) {
        background-color: #9999ff;
         text-align:center;
    }

希望对你有帮助!

【讨论】:

  • 非常好的解决方案,从来没有这样想过,很高兴学到新东西。
  • 是的,这些都非常灵活!
【解决方案3】:

添加一个额外的容器会给你更多的控制:

<div class="container">
    <div class="block">1</div>
    <div class="wrap">
        <div class="block">2</div>
        <div class="block">3</div>
    </div>
    <div class="block right">4</div>
</div>

.wrap{width:50px;margin:0 auto}
.block{float:left;width:25px;text-align:center}
.right{float:right}

【讨论】:

  • 感谢您的意见,这将对我未来的项目有所帮助!
猜你喜欢
  • 2023-03-03
  • 1970-01-01
  • 2011-10-01
  • 1970-01-01
  • 2018-10-08
  • 2021-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多