边距左边距:自动元素=填充左边100%宽度溢出项目 [英] Left margin of Margin: auto-ed elements = to padding left of 100%-width overflow item
问题描述
让我演示下列HTML的问题:
Let me demonstrate the problem with the following HTML:
<section style="text-align: center;">
<header style="margin: 0px auto; width: 300px; background: orange;"> </header>
<div>
<article style="overflow-x: auto; width: 100%; background: pink;">
<img src="http://placekitten.com/10000/10" />
</article>
</div>
</section>
我希望
IMG
元素与页面左边的距离与 header
元素的距离相同。我想要这是真的,无论用户调整浏览器的宽度。
The 'article
' element in there; I'd like the IMG
element in there to be the same distance from the left of the page as the header
element. I want this to be true regardless of how wide the user resizes their browser.
我想用CSS做。
And I want to do it with CSS only. You can add new elements, but not within the 'article
' tag.
您可以添加新的元素,但不能在我想这是不可能的,如果不困难。我有几个想法,但你能帮忙吗?
I imagine this to be impossible, if not difficult. I had a few ideas, but could you help?
推荐答案
calc c>方法
这可以通过(实验) calc
属性来完成:
div article {
margin-left: calc(50% - 300px/2);
}
这里必须输入 < header>
(在这种情况下 300px
),它会自动确定 50%
是。如果您更改< header>
的样式,并且太多浏览器不支持。
Here you'd have to enter the width of the <header>
(in this case 300px
) and it will automatically determine what 50% - (width) / 2
is. This won't automatically change if you change the style for the <header>
though, and it is not supported in too many browsers.
这是一个可以在每个现代浏览器中使用的方法:定义
定位,然后留下负值 margin
:
This is a method that would work in every modern browser: defining a left
positioning, and then a negative left margin
:
div article {
position:relative;
left: 50%;
margin-left: -150px;
}
首先将元素移动到网页上的50%宽度,然后通过其负边距将其向左移动150px。您必须输入< header>
的宽度,例如 calc()
方法,你必须自己除以2(不应太难:P)
This first moves the element to 50% width on the page, and then moves it 150px to the left via its negative margin. You will have to enter the width of the <header>
, like the calc()
method, but here you'll have to divide it by 2 yourself (shouldn't be too hard :P)
这篇关于边距左边距:自动元素=填充左边100%宽度溢出项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!