Program Tip

div에서 절대 위치 요소를 중앙에 배치하는 방법은 무엇입니까?

programtip 2020. 9. 27. 13:49
반응형

div에서 절대 위치 요소를 중앙에 배치하는 방법은 무엇입니까?


창 중앙에 div(with position:absolute;) 요소 를 배치해야합니다 . 그러나 너비를 알 수 없기 때문에 그렇게하는 데 문제 있습니다.

나는 이것을 시도했다. 그러나 너비가 반응하므로 조정해야합니다.

.center {
  left: 50%;
  bottom:5px;
}

어떤 아이디어?


<body>
  <div style="position: absolute; left: 50%;">
    <div style="position: relative; left: -50%; border: dotted red 1px;">
      I am some centered shrink-to-fit content! <br />
      tum te tum
    </div>
  </div>
</body>


이것은 나를 위해 작동합니다.

#content {
  position: absolute; 
  left: 0; 
  right: 0; 
  margin-left: auto; 
  margin-right: auto; 
  width: 100px; /* Need a specific value to work */
}
<body>
  <div>
    <div id="content">
      I'm the content
    </div>
  </div>
</body>


반응 형 솔루션

다음은 IE8 이하를 지원할 필요가없는 경우 반응 형 디자인 또는 일반적으로 알 수없는 크기대한 좋은 솔루션 입니다 .

.centered-axis-x {
    position: absolute;
    left: 50%;
    transform: translate(-50%, 0);
}

.outer {
    position: relative; /* or absolute */
    
    /* unnecessary styling properties */
    margin: 5%;
    width: 80%;
    height: 500px;
    border: 1px solid red;
}

.inner {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    
    /* unnecessary styling properties */
    max-width: 50%;
    text-align: center;
    border: 1px solid blue;
}
<div class="outer">
    <div class="inner">I'm always centered<br/>doesn't matter how much text, height or width i have.<br/>The dimensions or my parent are irrelevant as well</div>
</div>

다음은 JS Fiddle입니다.

단서는 left: 50%부모에 상대적인 반면 translate변환은 요소 너비 / 높이에 상대적이라는 것입니다.

이렇게하면 자식과 부모 모두에 유연한 너비가있는 완벽하게 중앙에있는 요소를 갖게됩니다. 보너스 : 자녀가 부모보다 더 큰 경우에도 작동합니다.

또한 다음과 같이 수직으로 중앙에 배치 할 수도 있습니다 (다시 말하지만 부모와 자식의 너비와 높이는 완전히 유연 할 수 있습니다 (및 / 또는 알 수 없음)).

.centered-axis-xy {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
}

transform공급 업체 접두사 가 필요할 수도 있습니다. 예를 들면-webkit-transform: translate(-50%,-50%);


정말 멋진 게시물 .. 누군가가 단일 div 태그로하고 싶다면 여기에 추가하고 싶었습니다.

촬영 width으로 900px.

#styleName {
    position: absolute;
    left: 50%;
    width: 900px;
    margin-left: -450px;
}

이 경우 width미리 알고 있어야 합니다.


앱솔루트 센터

HTML :

<div class="parent">
  <div class="child">
    <!-- content -->
  </div>
</div>

CSS :

.parent {
  position: relative;
}

.child {
  position: absolute;

  top: 0;
  right: 0;
  bottom: 0;
  left: 0;

  margin: auto;
}

데모 : http://jsbin.com/rexuk/2/

Google Chrome, Firefox 및 IE8에서 테스트되었습니다.

도움이 되었기를 바랍니다 :)


이 작업은 수직 및 수평

  #myContent{
        position: absolute;
        left: 0;
        right: 0;
        top:0;
        bottom:0;
        margin: auto;
   }

부모의 요소 중심을 만들고 싶다면 부모의 상대적 위치를 설정하십시오.

 #parentElement{
      position:relative
  }

편집하다:

  • 수직 중앙 정렬을 위해 요소에 높이를 설정하십시오. @Raul 덕분에

  • 부모의 요소 중심을 만들려면 부모의 위치를 ​​상대 위치로 설정하십시오.


솔루션을 검색하면서 위의 답변을 얻었고 Matthias Weiler 답변을 중심으로 콘텐츠를 만들 수 있지만 텍스트 정렬을 사용합니다.

#content{
  position:absolute;
  left:0;
  right:0;
  text-align: center;
}

크롬과 파이어 폭스에서 작업했습니다.


나는이 질문에 이미 몇 가지 답변이 있음을 이해하지만 거의 모든 클래스에서 작동하는 솔루션을 찾지 못했지만 의미가 있고 우아하므로 여기에 몇 가지 조정 후 내 의견이 있습니다.

.container {
    position: relative;
}

.container .cat-link {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate3d(-50%,-50%,0);
    z-index: 100;
    text-transform: uppercase; /* Forces CSS to treat this as text, not a texture, so no more blurry bugs */
    background-color: white;
}

.color-block {
  height: 250px;
  width: 100%;
  background-color: green;
}
<div class="container">
  <a class="cat-link" href="">Category</a>
  <div class="color-block"></div>
</div>

이것이 말하는 것은 나에게 a top: 50%와 a를 left: 50%다음 X / Y 축에서 -50%"거울 공간 만들기"라는 의미에서 값으로 변환 (공간 만들기)합니다 .

따라서 div의 모든 4 개 지점에 동일한 공간이 생성되며, 이는 항상 상자 (4면 포함)입니다.

이것은 :

  1. 부모의 높이 / 너비를 몰라도 작업합니다.
  2. 반응 형 작업.
  3. X 또는 Y 축에서 작업합니다. 내 예에서와 같이 둘 다.
  4. 나는 그것이 작동하지 않는 상황을 생각할 수 없습니다.

컨테이너 요소의 중앙에 배치하려는 절대 위치 요소의 임의의 알 수없는 너비에서 작동합니다.

데모

<div class="container">
  <div class="box">
    <img src="https://picsum.photos/200/300/?random" alt="">
  </div>
</div>

.container {
  position: relative;
  width: 100%;
}

.box {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

수평 및 수직으로도 중앙에 배치해야하는 경우 :

left: 50%;
top: 50%;
transform: translate(-50%, -50%);

내가 아는 한, 이것은 알려지지 않은 너비로 달성하는 것이 불가능합니다.

그것이 당신의 시나리오에서 작동한다면-100 % 너비와 높이의 보이지 않는 요소를 절대적으로 배치하고 여백을 사용하여 요소를 중앙에 놓을 수 있습니다 : auto 및 가능하면 vertical-align. 그렇지 않으면 Javascript가 필요합니다.


@bobince의 답변에 추가하고 싶습니다.

<body>
    <div style="position: absolute; left: 50%;">
        <div style="position: relative; left: -50%; border: dotted red 1px;">
            I am some centered shrink-to-fit content! <br />
            tum te tum
        </div>
    </div>
</body>

개선됨 : /// 중앙 div에 큰 요소가있는 가로 스크롤바가 나타나지 않습니다.

<body>
    <div style="width:100%; position: absolute; overflow:hidden;">
        <div style="position:fixed; left: 50%;">
            <div style="position: relative; left: -50%; border: dotted red 1px;">
                I am some centered shrink-to-fit content! <br />
                tum te tum
            </div>
        </div>
    </div>
</body>

이것은 우리에게 도움이 된 다른 답변의 혼합입니다.

.el {
   position: absolute;
   top: 50%;
   margin: auto;
   transform: translate(-50%, -50%);
}

여기에 유용한 jQuery 플러그인이 있습니다. 여기 에서 찾았 습니다 . CSS만으로는 가능하지 않다고 생각합니다.

/**
 * @author: Suissa
 * @name: Absolute Center
 * @date: 2007-10-09
 */
jQuery.fn.center = function() {
    return this.each(function(){
            var el = $(this);
            var h = el.height();
            var w = el.width();
            var w_box = $(window).width();
            var h_box = $(window).height(); 
            var w_total = (w_box - w)/2; //400
            var h_total = (h_box - h)/2;
            var css = {"position": 'absolute', "left": w_total+"px", "top":
h_total+"px"};
            el.css(css)
    });
};

내가 선호하는 센터링 방법 :

position: absolute;
margin: auto;
width: x%
  • 절대 블록 요소 위치 지정
  • 마진 자동
  • 동일한 왼쪽 / 오른쪽, 위 / 아래

여기에 JSFiddle


위의 반응 형 솔루션의 sass / compass 버전 :

#content {
  position: absolute;
  left: 50%;
  top: 50%;
  @include vendor(transform, translate(-50%, -50%));
}

이것은 나를 위해 일했습니다.

<div class="container><p>My text</p></div>

.container{
position: absolute;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
}

Flex를 사용하여 절대 위치 div를 중앙에 배치 할 수 있습니다.

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

.relative {
  width: 275px;
  height: 200px;
  background: royalblue;
  color: white;
  margin: auto;
  position: relative;
}

.absolute-block {
  position: absolute;
  height: 36px;
  background: orange;
  padding: 0px 10px;
  bottom: -5%;
  border: 1px solid black;
}

.center-text {
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 1px 2px 10px 2px rgba(0, 0, 0, 0.3);
}
<div class="relative center-text">
  Relative Block
  <div class="absolute-block center-text">Absolute Block</div>
</div>


이미 답변을 제공했으며 이전 답변과 다른 답변이 잘 작동한다는 것을 알고 있습니다. 그러나 나는 과거에 이것을 사용했으며 특정 브라우저와 특정 상황에서 더 잘 작동합니다. 그래서 이드도이 대답을한다고 생각했습니다. 나는 이것이 완전히 별개의 대답이고 내가 제공 한 두 가지가 관련이 없다고 생각하기 때문에 이전 답변을 "편집"하지 않고 추가하지 않았습니다.

HTML :

<div id='parent'>
  <div id='child'></div>
</div>

CSS :

#parent {
  display: table;
}
#child {
  display: table-cell;
  vertical-align: middle;
}

#container
{
  position: relative;
  width: 100%;
  float:left
}
#container .item
{
  width: 50%;
  position: absolute;
  margin: auto;
  left: 0;
  right: 0;
}

HTML

<div id='parent'>
  <div id='centered-child'></div>
</div>

CSS

#parent {
  position: relative;
}
#centered-child {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto auto;
}

http://jsfiddle.net/f51rptfy/


요소가있는 경우이 솔루션은 작동 widthheight

.wrapper {
  width: 300px;
  height: 200px;
  background-color: tomato;
  position: relative;
}

.content {
  width: 100px;
  height: 100px;
  background-color: deepskyblue;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
}
<div class="wrapper">
  <div class="content"></div>
</div>


이 질문에 대한 해결책이 제 경우에 효과가 없었습니다. 일부 이미지에 대한 캡션을 작성 중이고 이것을 사용하여 해결했습니다.

top: 0;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;

display: flex;
align-items: center;

figure {
  position: relative;
  width: 325px;
  display: block
}


figcaption{
   
    position: absolute;
    background: #FFF;
    width: 120px;
    padding: 20px;

    -webkit-box-shadow: 0 0 30px grey;
    box-shadow: 0 0 30px grey;
    border-radius: 3px;
    display: block;
    
    top: 0;
    left: 0;
    right: 0;
    margin-left: auto;
    margin-right: auto;
    
    display: flex;
    align-items: center;
}
<figure>
  <img  src="https://picsum.photos/325/600">
  <figcaption> 
			But as much
    </figcaption>
                
</figure>


HTML :

<div class="wrapper">
    <div class="inner">
        content
    </div>
</div>

CSS :

.wrapper {
    position: relative;

    width: 200px;
    height: 200px;

    background: #ddd;
}

.inner {
    position: absolute;
    top: 0; bottom: 0;
    left: 0; right: 0;
    margin: auto;

    width: 100px;
    height: 100px;

    background: #ccc;
}

여기에 더 많은 예


이것은 DIV가 페이지 중앙에 정확히 떠오르게하기 위해 알아 낸 트릭입니다. 물론 정말 못 생겼지 만 모두에서 작동합니다.

점과 대시

<div style="border: 5 dashed red;position:fixed;top:0;bottom:0;left:0;right:0;padding:5">
    <table style="position:fixed;" width="100%" height="100%">
        <tr>
            <td style="width:50%"></td>
            <td style="text-align:center">
                <div style="width:200;border: 5 dashed green;padding:10">
                    Perfectly Centered Content
                </div>
            </td>
            <td style="width:50%"></td>
        </tr>
    </table>
</div>

청소기

와우, 5 년이 흘렀 잖아요?

<div style="position:fixed;top:0px;bottom:0px;left:0px;right:0px;padding:5px">
<table style="position:fixed" width="100%" height="100%">
    <tr>
        <td style="width:50%"></td>
        <td style="text-align:center">
            <div style="padding:10px">
                <img src="Happy.PM.png">
                <h2>Stays in the Middle</h2>
            </div>
        </td>
        <td style="width:50%"></td>
    </tr>
</table>


.center {
  position: absolute
  left: 50%;
  bottom: 5px;
}

.center:before {
    content: '';
    display: inline-block;
    margin-left: -50%;
}

이미지를 div에 배치하고 div ID를 추가하고 해당 div의 CSS에 text-align:center

HTML :

<div id="intro_img">

    <img src="???" alt="???">

</div>

CSS :

#intro_img {
    text-align:center;
}

#content { margin:0 auto; display:table; float:none;}
<body>
  <div>
    <div id="content">
      I'm the content
    </div>
  </div>
</body>


폭을 알 수없는 블록을 수평으로 중앙에 배치하는 간단한 방법 :

<div id="wrapper">
  <div id="block"></div>
</div>

#wrapper { position: absolute; width: 100%; text-align: center; }
#block { display: inline-block; }

텍스트 정렬 속성을 #block 규칙 세트에 추가하여 블록 정렬에 관계없이 내용을 정렬 할 수 있습니다.

이것은 Firefox, Chrome, IE, Edge 및 Safari의 최신 버전에서 작동했습니다.


또한 미들웨어 만들 수 있습니다 div#centered에 중심 상자 absolute, leftright특성과없이 width설정 한 후 메인 컨텐츠 속성을하고 div와 자식으로 display:inline-block와 상자와 센터를 text-align:center자사의 미들웨어 부모 상자 세트를

#container{
  position: relative;
  width: 300px;
  height: 300px;
  border: solid 1px blue;
  color:#dddddd;
}

#centered{
  position: absolute;
  text-align: center;
  margin: auto;
  top: 20px;
  left:0;
  right:0;
  border: dotted 1px red;
  padding: 10px 0px;
  
  
}

#centered>div{
  border: solid 1px red;
  display:inline-block;
  color:black;
}
<div id="container">
  hello world hello world
  hello world hello world
  hello world hello world
  hello world hello world
  hello world hello world
  hello world hello world
  hello world hello world
  hello world hello world
  
  <div id="centered">
    <div>
      hello world <br/>
      I don't know my width<br/>
      but I'm still absolute!  
    </div>
  </div>

</div>

참고 URL : https://stackoverflow.com/questions/1776915/how-to-center-absolutely-positioned-element-in-div

반응형