Center the HTML element

What is the correct way to position an HTML element according to the center handle?

In this example:

  XXXXXXXXX
      |
      |
     123px

Suppose that the element should be in absolute position left: 123px;, but the text should be centered at this point, and not begin with it. The text of the element is dynamic, so I cannot set it to static negative margin-left.

Is there a clean CSS way for this? The JS method of measuring offsetWidthand then setting leftafter calculation width / 2will not work in my case due to various limitations.

+4
source share
3 answers

, . - HTML , .

, inline-block, (123px), -50%. , , .

#container {
  position: relative;
}
#line {
  width: 100px;
  height: 100px;
  left: 123px;
  position: absolute;
  border-left: 1px solid red;
}
#text {
  left: 123px;
  top: 50px;
  display: inline-block;
  position: relative;
}
#text p {
  position: relative;
  background: green;
  margin-left: -50%;
  display: inline-block;
  color: #fff;
  text-align: center;
  padding: 10px;
  box-sizing: border-box;
}
<div id="container">
<div id="line">
 &lt;-- 123px
</div>
<div id="text">
<p>
This is some dynamic text<br>the div has no absolute set width.
</p>
</div></div>

, , , / HTML. flex-box, .

, fiddle.

+2

- X -50%

p {
  position: relative;
  display: inline-block;
      left: 100px;
    transform: translateX(-50%);
}
<p>ONE</p>
<br>
<p>TWO, LONGER</p>
<br>
<p>THREE, the longest</p>
+4

css:

:

.element{
    width: 200px; /* Full width */
    left: 50%;
    margin-left: -100px; /* Half width */
    position: absolute;
    display: block;
}

, css3:

.element{
    width: 200px; /* Full width */
    left: calc(50% - 100px);
    position: absolute;
    display: block;
}

You may also have a non-absolute approach , but the position of the parent should be relative :

.element-parent{
    position: relative;
}

.element-parent .element{
    margin: 0 auto;
}

If you use a text element (inline block), this works with IE 7 +:

.element-parent{
    text-align: center;
}

.element-parent .element{
    display: inline-block;
}
+1
source

Source: https://habr.com/ru/post/1629889/


All Articles