Html 按中心点定位,而不是左上点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15328416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 06:19:09  来源:igfitidea点击:

Position by center point, rather than top-left point

htmlcsspositionpositioningcss-position

提问by kaboom1

Is it possible to tell the code to position by the center point of an element, rather than by the top-left point? If my parentelement has

是否可以告诉代码通过元素的中心点而不是左上点来定位?如果我的元素有

width: 500px;

and my childelement has

我的元素有

/*some width, for this example let's say it's 200px*/
position: absolute;
left: 50%;

one would assume that based on the 50%positioning, the child element will be in the middle of the parent, leaving 150pxof free space on each side. However, it is not, since it is the top-left point of the child that goes to 50%of the parent's width, therefore the whole child's width of 200pxgoes to the right from there, leaving 250pxof free space on the left and only 50pxon the right.

人们会假设基于50%定位,子元素将位于父元素的中间,150px在每一侧留下可用空间。然而,事实并非如此,因为它是孩子的​​左上角到达50%父母的宽度,因此整个孩子的宽度200px从那里向右移动,250px在左侧留下可用空间,仅50px在右侧.

So, my question is, how to achieve center positioning?

所以,我的问题是,如何实现中心定位

I found this solution:

我找到了这个解决方案:

position: absolute;
width: 200px;
left: 50%;
margin-left: -100px;

but I don't like it because you need to edit it manually for each element's width - I would like something that works globally.

但我不喜欢它,因为您需要为每个元素的宽度手动编辑它 - 我想要一些全局有效的东西。

(For example, when I work in Adobe After Effects, I can set a position for an object and then set specific anchor point of that object that will be put to that position. If the canvas is 1280pxwide, you position an object to 640pxand you choose the center of the object to be your anchor point, then the whole object will be centered within the 1280pxwide canvas.)

(例如,当我在Adobe工作的影响后,我可以设置一个位置的对象,然后设置将被投入到那个位置该对象的特定锚点。如果画布是1280px宽,你的目标定位到640px你选择对象的中心作为锚点,然后整个对象将在1280px宽画布内居中。)

I would imagine something like this in CSS:

我会在 CSS 中想象这样的事情:

position: absolute;
left: 50%;
horizontal-anchor: center;

Similarly, horizontal-anchor: rightwould position the element by its right side, so the whole content would be to the left from the point of its parent's 50%width.

同样,horizontal-anchor: right将元素放置在其右侧,因此整个内容将位于其父级50%宽度点的左侧。

And, the same would apply for vertical-anchor, you get it.

而且,同样适用于vertical-anchor,你明白了。

So, is something like this possible using only CSS(no scripting)?

那么,使用CSS(无脚本)就可以实现这样的事情吗?

Thanks!

谢谢!

回答by John

If the element must be absolutely positioned (so, margin: 0 auto;is of no use for centering), and scripting is out of the question, you could achieve this with CSS3 transforms.

如果元素必须绝对定位(因此,margin: 0 auto;对于居中没有用处),并且脚本编写是不可能的,那么您可以使用 CSS3 转换来实现这一点。

.centered-block {
    width: 100px; 
    left: 50%; 
    -webkit-transform: translate(-50%, 0); 
    position: absolute;
}

See this fiddlefor some examples. The important parts: left: 50%;pushes block halfway across its parent (so its left side is on the 50% mark, as you mentioned). transform: translate(-50%, 0);pulls the block half it's ownwidth back along the x-axis (ie. to the left), which will place it right in the center of the parent.

有关一些示例,请参阅此小提琴。重要的部分:left: 50%;将块推到其父级的中间(所以它的左侧是 50% 标记,正如你所提到的)。transform: translate(-50%, 0);将块沿 x 轴(即向左)拉回其自身宽度的一半,这会将其放置在父项的右侧。

Note that this is unlikely to be cross-browser compatible, and will still require a fall back of some sort for old browsers.

请注意,这不太可能跨浏览器兼容,并且仍然需要对旧浏览器进行某种回退。

回答by Sandy Gifford

If adding another element is an option, consider the following:

如果添加另一个元素是一种选择,请考虑以下事项:

(View the following code live here)

在此处查看以下代码

HTML:

HTML:

<div class="anchor" id="el1">
    <div class="object">
    </div>
</div>
<div class="anchor" id="el2">
    <div class="object">
    </div>
</div>

CSS:

CSS:

/* CSS for all objects */

div.object
{
    width:               100%;
    height:              100%;
    position:            absolute;
    left:                -50%;
    top:                 -50%; /* to anchor at the top center point (as opposed to true center) set this to 0 or remove it all together */
}

div.anchor
{
    position:            absolute; /* (or relative, never static) */
}


/* CSS for specific objects */

div#el1
{
    /* any positioning and dimensioning properties for element 1 should go here */
    left:                100px;
    top:                 300px;
    width:               200px;
    height:              200px;
}

div#el2
{
    /* any positioning and dimensioning properties for element 2 should go here */
    left:                400px;
    top:                 500px;
    width:               100px;
    height:              100px;
}

div#el1 > div.object
{
    /* all other properties for element 1 should go here */
    background-color:    purple;
}

div#el2 > div.object
{
    /* all other properties for element 2 should go here */
    background-color:    orange;
}

Essentially what we're doing is setting up one object to define the position, width and height of the element, and then placing another one inside of it that gets offset by 50%, and gets it's parent dimensions (ie width: 100%).

本质上,我们正在做的是设置一个对象来定义元素的位置、宽度和高度,然后在其中放置另一个偏移 50% 的对象,并获取它的父尺寸(即width: 100%)。

回答by Kay Angevare

Stumbled upon this question, and I'd like to add another way to center content within a div.

偶然发现了这个问题,我想添加另一种方法来将 div 中的内容居中。

By using the CSS3 display mode 'flexible box', as in setting the following CSS properties to the parent div

通过使用 CSS3 显示模式 'flexible box',如将以下 CSS 属性设置为父 div

display: flex;
position: relative;
align-items: center;
justify-content:center;

And 'at least' setting the following properties to the child div

并且“至少”将以下属性设置为子 div

position:relative;

The browser will automatically center the contents within the parent div, unaffected by their width or height, this particularly comes in handy when you're developing something like an image grid or just want to remove the hassle of calculating a divs position, then having to recalculate it when you change your mind about the set-up of said div.

浏览器会自动将父 div 中的内容居中,不受其宽度或高度的影响,这在您开发像图像网格之类的东西或只是想消除计算 div 位置的麻烦时特别有用,然后不得不当您改变主意设置所述 div 时,重新计算它。

In my own work, I tend to set-up a class named

在我自己的工作中,我倾向于设置一个名为

.center-center

With the properties I described for the parent div, then just add it to whatever element of which I need its contents centered.

使用我为父 div 描述的属性,然后只需将它添加到我需要其内容居中的任何元素。

I've created a JSFiddle to support this explanation, feel free to click on the red squares to see the positioning in action.

我已经创建了一个 JSFiddle 来支持这个解释,请随意点击红色方块以查看正在运行的定位。

https://jsfiddle.net/f1Lfqrfs/

https://jsfiddle.net/f1Lfqrfs/

For multi-line support, you can add (or uncomment in the JSF) the following CSS property to the parent DIV

对于多行支持,您可以向父 DIV 添加(或在 JSF 中取消注释)以下 CSS 属性

flex-wrap: wrap;

回答by Melinda Chang

Here's one way to center a text element in the middle of the container (using a header as an example

这是在容器中间居中文本元素的一种方法(以标题为例

CSS:

CSS:

.header {
     text-align: center;
     top: 50%;
     left: 50%;
     transform: translate(-50%, -50%);
     position: absolute;
}

It centers by a middle anchor point.

它以中间锚点为中心。

回答by manikanta

I got it working by using transform: translateXwith calcfor horizonally positioning by element center instead of top-left. Same trick can be used for vertical using transform: transformY. This will work with width of any type (try resizing)

我通过使用transform: translateXwithcalc来按元素中心而不是左上角水平定位来使其工作。相同的技巧可用于垂直使用transform: transformY。这适用于任何类型的宽度(尝试调整大小)

Snippet: transform: translateX(calc(-50% + 223px));

片段: transform: translateX(calc(-50% + 223px));

Browser support: https://caniuse.com/#feat=transforms2d, https://caniuse.com/#feat=calc

浏览器支持:https: //caniuse.com/#feat=transforms2d,https: //caniuse.com/#feat=calc

Codepen for more examples: https://codepen.io/manikantag/pen/KJpxmN

Codepen 获取更多示例:https://codepen.io/manikantag/pen/KJpxmN

Note on offsetLeft/offsetTop etc: el.offsetLeftwill not given proper value for CSS transformed elements. You would require something like el.getBoundingClientRect().left - el.offsetLeft - el.parentNode.offsetLeft(as mentioned here)

关于 offsetLeft/offsetTop 等的注意事项:el.offsetLeft不会为 CSS 转换元素提供适当的值。你需要类似el.getBoundingClientRect().left - el.offsetLeft - el.parentNode.offsetLeft如这里提到的

Note about flow effect:as detailed in CSS Things That Don't Occupy Space, transform doesn't effect the following element without considering the offset caused by transform. Sometimes this may not be the intended behavior. This can be fixed using negative margins if width/height are fixed (doesn't work if width/height are using %)

关于流效果的注意事项:CSS Things That Don't Occupy Space 中所述,如果不考虑由变换引起的偏移,变换不会影响以下元素。有时这可能不是预期的行为。如果宽度/高度是固定的,这可以使用负边距来修复(如果宽度/高度正在使用则不起作用%

.left-positioned {
  margin-left: 223px;
  background-color: lightcoral;
}

.center-positioned {
  transform: translateX(calc(-50% + 223px)); /*=====> actual solution */
  background-color: cyan;
}

.with-width {
  width: 343px;
  background-color: lightgreen;
}


/* styles not related to actual solution */

div {
  resize: both;
  overflow: auto;
}

.container {
  background-color: lightgray;
}

.ele {
  display: inline-block;
  height: 70px;
  text-align: center;
}
<div class="container">
  <div class="ele left-positioned">Reference element (left at 223px)</div> <br/>
  <div class="ele center-positioned">^<br/>Center positioned element (center at 223px)</div> <br/>
  <div class="ele center-positioned with-width">^<br/>Center positioned element with width (center at 223px)</div>
</div>

回答by Ali Bassam

left:50% doesn't center the center of gravity of this div 50% to the left, it is the distance between the left border and the left border of the parent element, so basically you need to do some calculations.

left:50% 并不是将这个div的重心50%向左居中,它是左边框和父元素左边框之间的距离,所以基本上你需要做一些计算。

left = Width(parent div) - [ Width(child div) + Width(left border) + Width(right border) ]

left = left / 2

So you can do a Javascript function...

所以你可以做一个Javascript函数......

function Position(var parentWidth, var childWith, var borderWidth)
{
      //Example parentWidth = 400, childWidth = 200, borderWidth = 1
      var left = (parentWidth - ( childWidth + borderWidth));
      left = left/2;
      document.getElementById("myDiv").style.left= left+"px";
}