etc./StackOverFlow

div에서 절대 위치 요소를 어떻게 가운데에 맞출 수 있습니까?

청렴결백한 만능 재주꾼 2023. 4. 25. 10:56
반응형

질문자 :Ish


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

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

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

어떻게하니?



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

 #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>


Matthias Weiler

 <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>


bobince

반응형 솔루션

다음은 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 바이올린입니다.

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

이렇게 하면 자식과 부모 모두에 유연한 너비가 있는 완벽하게 중심에 있는 요소가 있습니다. 보너스: 이것은 자식이 부모보다 크더라도 작동합니다.

다음과 같이 세로로 가운데에 놓을 수도 있습니다(다시 말하지만 부모와 자식의 너비와 높이는 완전히 유연할 수 있습니다(및/또는 알 수 없음)).

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

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


ProblemsOfSumit

누군가가 단일 div 태그로 작업을 수행하려는 경우 추가하고 싶었습니다. 탈출구는 다음과 같습니다.

width900px 로 취합니다.

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

이 경우 width 미리 알아야 합니다.


pratikabu

<div style='position:absolute; left:50%; top:50%; transform: translate(-50%, -50%)'> This text is centered. </div>

이렇게 하면 위치 유형이 static 또는 relative인 div 내부의 모든 객체가 가운데에 맞춰집니다.


Utkarsh Tyagi

절대 중심

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 및 Internet Explorer 8 에서 테스트되었습니다.


Ijas Ameenudeen

이것은 수직 및 수평에 대해 작동합니다.

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

그리고 요소를 부모의 중심으로 만들려면 부모의 상대적 위치를 설정하십시오.

 #parentElement{ position: relative }
  • 수직 중앙 정렬의 경우 높이를 요소로 설정하십시오. 라울 덕분에 .

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


Mohsen Abdollahi

반응형 솔루션

div의 요소를 가정하면 다른 div는 ...

이 솔루션은 잘 작동합니다.

 <div class="container"> <div class="center"></div> </div>

컨테이너 는 모든 크기가 될 수 있습니다(위치에 상대적이어야 함).

 .container { position: relative; /* Important */ width: 200px; /* Any width */ height: 200px; /* Any height */ background: red; }

요소( div )는 어떤 크기도 될 수 있습니다( 컨테이너보다 작아야 함 ).

 .center { position: absolute; /* Important */ top: 50%; /* Position Y halfway in */ left: 50%; /* Position X halfway in */ transform: translate(-50%,-50%); /* Move it halfway back(x,y) */ width: 100px; /* Any width */ height: 100px; /* Any height */ background: blue; }

결과는 다음과 같습니다. 코드 조각을 실행합니다.

 .container { position: relative; width: 200px; height: 200px; background: red; } .center { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 100px; height: 100px; background: blue; }
 <div class="container"> <div class="center"></div> </div>

나는 그것이 매우 도움이된다는 것을 알았습니다.


Michiel J Otto

가로 및 세로로 가운데 정렬해야 하는 경우:

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

michal.jakubeczy

솔루션을 검색하면서 이전 답변을 얻었고 Matthias Weiler의 답변을 중심으로 콘텐츠를 만들 수 있었지만 text-align .

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

그것은 구글 크롬과 파이어 폭스와 함께 작동했습니다.


cavila

나는 이 질문에 이미 몇 가지 답이 있다는 것을 이해하지만, 거의 모든 수업에서 작동하는 이치에 맞고 우아한 솔루션을 찾지 못했습니다.

 .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>

그것은 나에게 top: 50% 및 a left: 50% 를 제공한 다음 X/Y 축 모두에서 "거울 공간 생성"이라는 의미에서 -50%

따라서 이것은 항상 상자(4면이 있음)인 div의 네 점 모두에 동일한 공간을 만듭니다.

이렇게 하면:

  1. 부모의 높이/너비를 알 필요 없이 작업하세요.
  2. 반응형 작업을 합니다.
  3. X 또는 Y축에서 작업합니다. 또는 내 예에서와 같이 둘 다.
  4. 작동하지 않는 상황을 생각해낼 수 없습니다.

Daniel Moss

이것은 우리를 위해 일한 다른 답변의 혼합입니다.

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

Crashalot

이것은 컨테이너 요소의 중앙에 갖고 싶은 절대 위치 요소의 임의의 알 수 없는 너비에서 작동합니다.

데모

 <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; }

lowtechsun

Flexbox 는 절대 위치 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>


Dhaval Jardosh

내가 아는 한, 이것은 알 수 없는 너비에 대해 달성할 수 없습니다.

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


Pekka

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>

Vial

다음은 이를 수행하는 유용한 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) }); };

Ben Shelock

이전 반응형 솔루션 의 Sass / Compass 버전:

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

Adam Spence

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

 <div class="container><p>My text</p></div> .container{ position: absolute; left: 0; right: 0; margin-left: auto; margin-right: auto; }

Alan

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

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

JSFiddle이 여기에 있습니다 .


vp_arth

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

Burcu AKCAOGLU

HTML:

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

CSS:

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

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


Dustin Poissant

이 질문에 대한 허용된 솔루션이 제 경우에는 효과가 없었습니다...

일부 이미지에 대한 캡션을 작성 중이며 다음을 사용하여 해결했습니다.

 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>


Marcogomesr

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/


Dustin Poissant

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>


Mo.

.center { position: absolute left: 50%; bottom: 5px; } .center:before { content: ''; display: inline-block; margin-left: -50%; }

AndreyP

이것은 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> </div>

Mr. B

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; }

이것 과 더 많은 예제 는 여기 에 있습니다 .


user3102226

너비를 알 수 없는 블록을 수평으로 가운데에 맞추는 간단한 접근 방식:

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

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

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

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


Terence Bandoian

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


amit bende

출처 : http:www.stackoverflow.com/questions/1776915/how-can-i-center-an-absolutely-positioned-element-in-a-div

반응형