保证金的左边距:自动修改的元素=填充100%-width溢出项目的左边

时间:2014-01-30 20:09:44

标签: html css

让我用以下HTML演示问题:

<section style="text-align: center;">
  <header style="margin: 0px auto; width: 300px; background: orange;">&nbsp;</header>
  <div>
    <article style="overflow-x: auto; width: 100%; background: pink;">
      <img src="http://placekitten.com/10000/10" />
    </article>
  </div>
</section>

那里的'article'元素;我希望其中的IMG元素与页面左侧的距离与header元素的距离相同。无论用户调整浏览器的宽度,我都希望这是真的。

我只想用CSS做。 您可以添加新元素,但不能添加到“article”代码中。

我想这不可能,如果不是困难的话。我有一些想法,但你可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

calc()方法

这可以通过(实验性)calc属性完成:

div article {
    margin-left: calc(50% - 300px/2);
}

Demo

在这里,您必须输入<header>的宽度(在这种情况下为300px),它会自动确定50% - (width) / 2是什么。如果您更改<header>和[{3}}的样式,则不会自动更改。

margin-leftleft方法

这是一种适用于所有现代浏览器的方法:定义left定位,然后定义左侧margin

div article {
    position:relative;
    left: 50%;
    margin-left: -150px;
}

it is not supported in too many browsers

首先将元素移动到页面上的50%宽度,然后通过其负边距将其向左移动150px。你必须输入<header>的宽度,就像calc()方法一样,但在这里你必须自己将它除以2(不应该太难:P)

相关问题