【问题标题】:Align a fixed width div in center between two auto adjusting divs在两个自动调整 div 之间居中对齐一个固定宽度的 div
【发布时间】:2015-07-12 15:31:42
【问题描述】:

如何显示一个固定宽度为 800px 的 div,并且在两侧(左右)应该有自动调整的 div。到目前为止,我已经尝试在左侧自动调整 div 上使用 float:left ,在中心 div 上使用 widht:800px 在自动调整右侧 div 上使用 float:right ,但它不起作用。

这就是我到目前为止所得到的。 注意:center div 的背景是黑色的,三个 div 都包含在容器 div 中,容器 div 的背景颜色为红色。

HTML 代码

<body>
        <div id="outerSideContainerLeft" style:"float:left">
        left

        </div>

        <div id="feedContainer">
        center
        </div>

        <div id="outerSideContainerRight" style:"float:right">
        right               
        </div>

</body>

CSS 代码

div{
    display:inline-block;
}
#feedContainer{
    margin:0px;
    width:800px;
    background-color: black;
}

#outerSideContainerLeft
{
 background-color: blue;
 width: calc(49%-400px);
}

#outerSideContainerRight
{
 background-color: green;
 width: calc(49%-400px);
}

【问题讨论】:

  • 尝试一个包含 3 个单元格的表格。将固定宽度设置为仅中间单元格并使表格宽度为 100% 左右单元格将自动调整其宽度。
  • @gp。不能使用表格,网络爬虫不太重视表格内容,我希望我的网站进行 SEO 优化。

标签: html css


【解决方案1】:

试试this

这只是将inline-block 用于display,并将calc 属性用于左/右框的宽度。

请记住,一旦屏幕太窄,左/右框会互相下方。您可以使用媒体查询来更改布局,使其像this 一样响应式

calc 属性基本上会为您计算一个值。我给出的例子,你有一个宽度为 200px 的中间 div。所以右/左框需要是窗口整个宽度的 50% 减去中间框大小的一半。

所以 50% 的窗口减去 100px,这将为它们提供相对合适的宽度,以便它们填充固定宽度中间 div 周围的线。

不过,使用 inline-block 时有一个奇怪的边距,所以我改用 49% 来解释边距。

【讨论】:

  • 你能解释一下`width: calc(49% - 100px);`
  • 我理解了计算,但是calc函数是否包含在CSS中?
  • 是的,它包含在 css 中,但是一些旧的浏览器不支持它,请记住这一点
  • 我已经按照你说的做了,现在我得到了这个link,右边还有一些空白
  • 看起来您将所有三个盒子都放在某种容器中。那不会调整大小。您需要将容器宽度设置为 100%
【解决方案2】:

你可以试试新的 CSS3 flexbox。

查看this fiddle,如果这是您要查找的内容,我可以详细说明。

基本上,您的容器需要这种样式:

display: flex;

你的左右元素需要这些样式:

flex-grow:   1;
flex-shrink: 1;

而你的中间元素需要这些样式:

flex-grow:   0;
flex-shrink: 0;

所以,对于看起来像这样的 HTML:

<div class="container">
    <div class="left">We keep content here. Blah blah blah blah blah. Also, blah blah blah.</div>
    <div class="mid">This is a fixed size.</div>
    <div class="right">Some other content goes here.</div>

你会像这样使用 CSS(见小提琴):

.container {
    color: white;
    background-color: red;
    padding: 1em 0;

    display: flex;
}
.left {
    background-color: blue;
    flex-shrink: 1;
    flex-grow:   1;
}
.mid {
    width: 600px;
    background-color: black;
    flex-shrink: 0;
    flex-grow:   0;
}
.right {
    background-color: green;
    flex-shrink: 1;
    flex-grow:   1;
}

另请参阅this guide 了解有关 flexbox 的更多信息。作为警告,旧浏览器根本不支持它。

【讨论】:

  • 我认为他希望其他两个 div 填充中间 div 的左/右侧,而不是低于/超过
  • 在我的电脑(Chrome 42)上,这显示了中间固定宽度的中间 div,左右 div 拉伸/收缩以适应中间 div 的左右两侧,而无需移动到不同的行。
  • @onsmith 虽然上面的答案解决了我的问题,但我尝试了你的fiddle,它提供的输出与我想要做的不同,即水平放置所有三个 div,但你的小提琴将它们垂直放置。谢谢你的帮助:-)
猜你喜欢
  • 1970-01-01
  • 2017-05-26
  • 2013-04-04
  • 1970-01-01
  • 2021-11-04
  • 1970-01-01
  • 1970-01-01
  • 2013-11-25
  • 1970-01-01
相关资源
最近更新 更多