"위치 : 절대"요소를 중심에 배치하는 방법


678

속성이로 position설정된 요소를 가운데에 배치하는 데 문제 가 absolute있습니다. 왜 이미지가 중앙에 있지 않은지 아십니까?

body {
  text-align: center;
}

#slideshowWrapper {
  margin-top: 50px;
  text-align: center;
}

ul#slideshow {
  list-style: none;
  position: relative;
  margin: auto;
}

ul#slideshow li {
  position: absolute;
}

ul#slideshow li img {
  border: 1px solid #ccc;
  padding: 4px;
  height: 450px;
}
<body>
  <div id="slideshowWrapper">
    <ul id="slideshow">
      <li><img src="img/dummy1.JPG" alt="Dummy 1" /></li>
      <li><img src="img/piano_unlicened.JPG" alt="Dummy 2" /></li>
    </ul>
  </div>
</body>


3
ul # slideshow에 고정 너비를 지정해야합니다.
— ptriek

답변:


1193

너비를 설정 한 경우 다음을 사용할 수 있습니다.

position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
text-align: center;

21
이것은 다른 것보다 훨씬 깨끗한 대답입니다! 경고가 있습니까?
— sbichenko

8
가장 똑똑한 답변. 방금 확인했으며 모든 브라우저에서 작동합니다. IE8에서는 작동하지 않지만 IE> = 9에서는 작동합니다.
— Roger

13
IE에서 테스트해야합니다,이 트릭은하지 않습니다 작업 요소는 IE9에서 설정 '최대 폭'이있는 경우
— aphax

33
개인적으로 "여백 : 0 자동; 왼쪽 : 0; 오른쪽 : 0;"
— 헥터 Ordonez

58
너비가 설정되어 있지 않으면 간단하게 작동하지 않습니다. 부모에 text-align : center가 있고 절대 위치 요소에 배경이 없지만 배경을 배치하면 실제로 전체 너비를 취하는 것을 볼 수 있습니다. translateX (-50 %) 답변이 정답입니다.
— Codemonkey

585

위치 지정된 1 요소 의 width/ height를 모르면 다음과 같이 정렬 할 수 있습니다.

여기 예

.child {
    position: absolute;
    top: 50%;  /* position the top  edge of the element at the middle of the parent */
    left: 50%; /* position the left edge of the element at the middle of the parent */

    transform: translate(-50%, -50%); /* This is a shorthand of
                                         translateX(-50%) and translateY(-50%) */
}

CSS Transform 이 IE9 이상에서 지원 된다는 점은 주목할 가치가 있습니다. (간결하게하기 위해 공급 업체 접두사 생략)


설명

추가 top/ left의 50%상기 부모의 중간으로 이동하고 요소의 상위 / 좌측 여백 모서리 translate()와 함수 (네가티브) 의 값 -50%의 크기의 절반에 의해 이동시킨다 소자. 따라서 요소가 중간에 배치됩니다.

이는 top/ left속성 의 백분율 값 이 상위 블록의 높이 / 너비와 관련 이 있기 때문입니다 (포함 블록을 작성 함).

에 대한 백분율 값이지만 변환 함수 폭 상대적 / 소자 자체의 높이 (실제로는 그것의 크기를 의미 하는 경계 박스 ) .translate()

단방향 정렬의 경우 translateX(-50%)또는 translateY(-50%)대신 사용하십시오.


1. position이외 의 요소 static. 즉 relative, absolute, fixed값.


65
이것이 최고의 답변이어야합니다!
— Chris Pine

3
환상적인! 많은 최고!
— Bhargav Ponnapalli

4
나는 이것에 대한 답과 좋은 설명을 어디서나 검색했습니다. 이것은 최고의 답변이며 훌륭한 설명입니다! 감사.
— Mike

5
수평 센터링 : position: absolute; left: 50%; transform: translateX(-50%);, 수직 센터링 : position: absolute; top: 50%; transform: translateY(-50%);.
— Константин Ван

1
그냥 지금은 그 발견 translate의 크기에 따라 요소를 번역, 재산을 자신 , 부모의 상관없이 크기입니다.
— Farzin Kanzi

185

absoluteCSS에서 배치 된 것을 중심으로하는 것은 다소 복잡합니다.

ul#slideshow li {
    position: absolute;
    left:50%;
    margin-left:-20px;

}

margin-left가운데에 맞추려는 요소의 너비를 (음수) 절반으로 변경하십시오 .


5
이 테스트 할 때 이미지 크기가 다른 경우 작동하지 않습니다, 그들은 여전히 서로에 스택
— 라이언 기븐스

3
해킹이 너무 심합니다 (거의 항상 CSS로 밝혀 짐). 그러나 굉장합니다! :-)
— Dr.Kameleon

1
나는 다른 대답의 영리함에 유혹을 받았지만 이것 만 믿을 수 있었다.
— Chris Schiffhauer 1

나는 Ryan과 같은 문제가 있었으므로 "baaroz"가 제안한 두 번째 답변을 시도해 보았습니다. 내 주요 DIV의 너비는 PX가 아닌 %로 표시되므로 다른 해상도도 지원합니다.
— UID

이것은 실제로 중심이 아닙니다. 이것은 더 오른쪽에 위치합니다
— Artsicle

82

수직 및 수평 정렬 중심

top: 0;
bottom: 0;
margin: auto;
position: absolute;
left: 0;
right: 0;

참고 : 요소는 너비와 높이를 설정해야합니다


1
왜 이것이 더 많은 표를 얻지 못하는지 모르겠습니다. 내가 알 수있는 한 모바일 브라우저를 포함한 모든 브라우저에서 작동합니다. 지원 측면에서보다 안정적인 솔기. 간단하고 쉽고 깨끗합니다 ...
— David Martins

1
이것이 더 나은 대답입니다. 만들기 위해서는 하나의 div 만 필요하고 left : 50 % ;, top : 50 %; 69+ 표를 얻은 솔루션과 같은
— 이안 S

지금까지 가장 좋은 대답은 여기에 오는 사람이 확인해야합니다!
— Abdo Adel

3
요소 height가 작동하려면 세트가 필요합니다 .
— alexbooots

55

간단한 CSS 트릭은 다음을 추가하십시오.

width: 100%;
text-align: center;

이것은 이미지와 텍스트 모두에서 작동합니다.


48

절대 요소를 중앙에 배치하려는 경우

#div {
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    width:300px; /* Assign a value */
    height:500px; /* Assign a value */
    margin:auto;
}

컨테이너를 왼쪽에서 오른쪽으로 가운데에 맞추려면 (위에서 아래로)

#div {
    position:absolute;
    left:0;
    right:0;
    width:300px; /* Assign a value */
    height:500px; /* Assign a value */
    margin:auto;
}

왼쪽에서 오른쪽으로 상관없이 컨테이너를 위에서 아래로 중앙에 배치하려는 경우

#div {
    position:absolute;
    top:0;
    bottom:0;
    width:300px; /* Assign a value */
    height:500px; /* Assign a value */
    margin:auto;
}

2015 년 12 월 15 일 현재 업데이트

몇 달 전에 또 다른 새로운 트릭을 배웠습니다. 상대 부모 요소가 있다고 가정합니다.

여기에 당신의 절대 요소가 있습니다.

.absolute-element { 
    position:absolute; 
    top:50%; 
    left:50%; 
    transform:translate(-50%, -50%); 
    width:50%; /* You can specify ANY width values here */ 
}

이를 통해 기존 솔루션보다 더 나은 답변이라고 생각합니다. 너비와 높이를 지정할 필요가 없기 때문입니다. 이것은 요소 자체의 내용을 조정합니다.


36

"위치 : 절대"요소를 중앙에 배치합니다.

.your-element {
  position: absolute;
  left: 0;
  right: 0;
  text-align: center; // or this ->  margin: 0 auto;
}

32

이것은 나를 위해 일했다 :

position: absolute;
left: 50%;
transform: translateX(-50%);

27

position : absolute 특성을 가운데에 배치하려면 div 너비의 left : 50 % 및 margin-left : -50 %를 설정해야합니다.

<!-- for horizontal -->
<style>
div.center{
 width:200px;
 left:50%;
 margin-left:-100px;
 position:absolute;
}
</style>


<body>
 <div class='center'>
  should be centered horizontaly
 </div>
</body>

수직 중심 절대의 경우 상단이 아닌 왼쪽으로 동일한 작업을 수행해야합니다. (참고 : html 및 body는 최소 높이 100 % 여야합니다.)

<!-- for vertical -->
<style>
 body,html{
  min-height:100%;
 }
 div.center{
  height:200px;
  top:50%;
  margin-top:-100px;
  position:absolute;
 }
</style>

<body>
 <div class='center'>
  should be centered verticaly
 </div>
</body>

그리고 둘 다를 위해 결합 될 수 있습니다

   <!-- for both -->
 <style>
 body,html{
  min-height:100%;
 }
 div.center{
  width:200px;
  height:50px
  left:50%;
  top:50%;
  margin-left:-100px;
  margin-top:-25px;
  position:absolute;
 }
</style>


<body>
 <div class='center'>
  should be centered
 </div>
</body>

16
    <div class="centered_content"> content </div>
    <style type="text/css">
    .centered_content {
       text-align: center;
       position: absolute;
       left: 0;
       right: 0;
    }
    </style>

데모보기 : http://jsfiddle.net/MohammadDayeh/HrZLC/

text-align: center; position: absolute추가 할 때 요소 와 함께 작동합니다left: 0; right: 0;


2
이 코드가 작동하는 이유에 대한 해설 또는 근거를 제공하십시오. 코드 응답 자체는 필연적으로 삭제 플래그가 지정됩니다.
— rayryeng

14

더 간단하고 최고입니다.

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

그런 다음 img 태그를 position : relative 속성이있는 태그에 다음과 같이 삽입해야합니다.

<div style="width:256px; height: 256px; position:relative;">
      <img src="photo.jpg"/>
</div>

8

아마 가장 짧은

position:absolute;
left:0;right:0;top:0;bottom:0;
margin:0 auto;

1
이것은 매우 훌륭하지만 수직 및 수평 중앙에
— 맞추기

7

요소의 너비를 모르는 경우이 코드를 사용할 수 있습니다.

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

바이올린 데모 : http://jsfiddle.net/wrh7a21r/

출처 : https://stackoverflow.com/a/1777282/1136132


@ NabiK.AZ이 예제는 요소의 너비를 모르는 경우에 유용합니다. 귀하의 예에서 너비를 div로 설정했습니다.
— joseantgv 2016 년

7

또는 이제 위치 절대 값과 함께 플렉스 박스를 사용할 수 있습니다.

.parent {
    position: relative;
    display: flex;
    justify-content: center;
}

.child {
    position: absolute;
}

이것은 너무 과소 평가되었습니다.
— Siege21x

5

여기에 이미지 설명을 입력하십시오

나는 당신이 무엇을 성취하고 싶은지 잘 모르겠지만,이 경우에는 width: 100%;당신의 ul#slideshow li의지를 추가 하는 것이 트릭을 수행합니다.

설명

img태그는 인라인 블록 요소입니다. 즉, 텍스트처럼 인라인으로 흐르지 만 블록 요소와 같이 너비와 높이가 있습니다. 당신의 CSS에서 두 가지가 있습니다 text-align: center;규칙이 적용 <body>과에 #slideshowWrapper이 코드에서이은, 모든 인라인 및 인라인 블록 아이 요소가 가장 가까운 블록 요소를 중심으로 할 수 있습니다 (BTW 중복되는) li태그. 모든 블록 요소는 width: 100%정적 흐름 ( position: static;) 인 경우 기본값입니다. 문제는 li태그를로 지정 position: absolute;하면 일반 정적 흐름에서 태그를 빼내 므로 내부 내용에 맞게 크기가 줄어들어 즉, width: 100%속성 을 "잃어버린다"는 것 입니다.


5

left: calc(50% - Wpx/2);W가 요소의 너비를 사용하면 나를 위해 일합니다.


W를 어떻게 결정합니까?
— Purplejacket

그는 "이미지"라고 말했다. 이상적으로는 웹용 이미지를 수행 할 때 불필요한 크기를 피하기 위해 이미지를 크기를 조정하는 대신 사용할 크기로 만들어야합니다 (큰 이미지를 만드는 경우) 작음) 또는 멍청함 (작은 이미지를 크게 만드는 경우). -jQuery를 사용하고 동적으로 스타일을 지정하는 경우 "imageElement.naturalHeight"및 "imageElement.naturalWidth"를 사용할 수 있지만 약간 복잡해집니다. 공평하게 말하면, 다른 많은 답변들도 그들의 기법이 작동하기 위해 이미지의 너비를 알아야합니다.
— Julix

실제로 W를 얻는 방법에 대해 잘 모를 경우 Chrome에서는 CTRL + Shift + i (개발자 도구)를 사용하고 CTRL + Shift + C (검사 모드)를 사용하여 요소 위로 마우스를 가져 가서 넓게 볼 수 있습니다. 원하는 너비를 결정하고 CSS에 "width : Wpx"를 추가 할 수도 있습니다.
— Julix

4

목록 항목이 가운데에 있지 않기 때문에 이미지가 가운데에 있지 않습니다. 텍스트 만 중앙에 위치합니다. 전체 목록을 중앙에 배치하거나 목록 내의 이미지를 중앙에 배치하여 원하는 위치를 지정할 수 있습니다.

수정 된 버전의 코드는 하단에 있습니다. 내 개정판에서 나는 목록과 그 안의 이미지를 모두 중심에 둡니다.

진실은 위치가 절대로 설정된 요소를 중앙에 둘 수 없다는 것입니다 .

그러나이 행동은 모방 될 수 있습니다!

참고 :이 지침은 img뿐만 아니라 모든 DOM 블록 요소와 함께 작동합니다.

  1. 이미지를 div 또는 다른 태그 (경우에 따라 li)로 둘러싸십시오.

    <div class="absolute-div">
      <img alt="my-image" src="#">
    </div>

    참고 : 이러한 요소에 지정된 이름은 특별하지 않습니다.

  2. CSS 또는 scss를 변경하여 div에 절대 위치를 지정하고 이미지를 중앙에 배치하십시오.

    .absolute-div {
      position: absolute;
    
      width: 100%; 
      // Range to be centered over. 
    
      // If this element's parent is the body then 100% = the window's width
    
      // Note: You can apply additional top/bottom and left/right attributes
      // i.e. - top: 200px; left: 200px;
    
      // Test for desired positioning.
    }
    
    .absolute-div img {
      width: 500px;
      // Note: Setting a width is crucial for margin: auto to work.
    
      margin: 0 auto;
    }

그리고 당신은 그것을 가지고 있습니다! 당신의 img가 중심에 있어야합니다!

귀하의 코드 :

이것을 시도하십시오 :

body
{
  text-align : center;
}

#slideshow
{
  list-style : none;
  width      : 800px;
  // alter to taste

  margin     : 50px auto 0;
}

#slideshow li
{
  position : absolute;
}

#slideshow img
{
  border  : 1px solid #CCC;
  padding : 4px;
  height  : 500px;
  width   : auto;
  // This sets the width relative to your set height.

  // Setting a width is required for the margin auto attribute below. 

  margin  : 0 auto;
}
<ul id="slideshow">
    <li><img src="http://lorempixel.com/500/500/nature/" alt="Dummy 1" /></li>
    <li><img src="http://lorempixel.com/500/500/nature/" alt="Dummy 2" /></li>
</ul>

도움이 되었기를 바랍니다. 행운을 빕니다!


3

상대 객체 내부의 절대 객체는 부모 객체와 관련이 있습니다. 여기서 문제는 컨테이너의 정적 너비가 필요 #slideshowWrapper하고 나머지 솔루션은 다른 사용자가 말한 것과 같습니다

body {
    text-align: center;
}

#slideshowWrapper {
    margin-top: 50px;
    text-align:center;
    width: 500px;
}

ul#slideshow {
    list-style: none;
    position: relative;
    margin: auto;
}

ul#slideshow li {
    position: relative;
    left: 50%;
}

ul#slideshow li img {
    border: 1px solid #ccc;
    padding: 4px;
    height: 450px;
}

http://jsfiddle.net/ejRTU/10/


두 이미지가 서로 쌓여있는 바이올린.
— Ryan Gibbons

3

다음은 "위치 : 절대"를 가진 중심 요소에 대한 쉽고 최상의 솔루션입니다.

 body,html{
  min-height:100%;
 }
 
 div.center{
 width:200px;
 left:50%;
 margin-left:-100px;/*this is 50% value for width of the element*/
 position:absolute;
 background:#ddd;
 border:1px solid #999;
 height:100px;
 text-align:center
 }
 
 
<style>

</style>

<body>
 <div class='center'>
  should be centered verticaly
 </div>
</body>


2

이 방법으로 시도 할 수 있습니다 :

* { margin: 0px; padding: 0px; }
#body { height: 100vh; width: 100vw; position: relative; 
        text-align: center; 
        background-image: url('https://s-media-cache-ak0.pinimg.com/originals/96/2d/ff/962dff2247ad680c542622e20f44a645.jpg'); 
         background-size: cover; background-repeat: no-repeat; }
.text { position: absolute; top: 0; bottom: 0; left: 0; right: 0; height:100px; 
        display: inline-block; margin: auto; z-index: 999999; }
<html>
<body>
	<div id="body" class="container-fluid">
	  <!--Background-->
	    <!--Text-->
		  <div class="text">
		    <p>Random</p>
		  </div>	  
	</div>
</body>
</html>


1

위치 절대 값은 흐름에서 빠져 나와 상위에 0x0에 배치합니다 (위치 절대 값 또는 위치 상대 값을 갖는 마지막 블록 요소).

나는 당신이 정확히 무엇을 성취하려고하는지 잘 모르겠습니다. 리를 a로 설정하는 것이 가장 좋을 position:relative것입니다. 현재 CSS가 주어지면

http://jsfiddle.net/rtgibbons/ejRTU/ 를 확인 하여 게임하십시오.


: // 끝에 당신과 거의 같은 해결책입니다 ... <Up vote
— eveevans

1
#parent
{
    position : relative;
    height: 0;
    overflow: hidden;
    padding-bottom: 56.25% /* images with aspect ratio: 16:9  */
}

img 
{
    height: auto!important;
    width: auto!important;
    min-height: 100%;
    min-width: 100%;
    position: absolute;
    display: block;
    /*  */
    top: -9999px;
    bottom: -9999px;
    left: -9999px;
    right: -9999px;
    margin: auto;
}

음의 상단, 오른쪽, 하단, 왼쪽 값을 사용하여 위에 나열된 센터링 방법을 본 위치를 기억하지 못합니다. 나를 위해,이 테크닉은 대부분의 상황에서 최고입니다.

위에서 조합을 사용하면 이미지가 다음 설정의 배경 이미지처럼 동작합니다.

background-position: 50% 50%;
background-repeat: no-repeat;
background-size: cover;

첫 번째 예에 대한 자세한 내용은 다음을 참조하십시오.
CSS로 div의 가로 세로 비율 유지


0

일어나고있는 것에는 두 가지 해결책이 있습니다. 여백을 사용하여 중앙에 맞추고 위치를 사용하여 중앙에 놓습니다. 둘 다 잘 작동하지만이 중심 요소를 기준으로 요소를 절대 위치에 배치하려면 두 번째 요소의 절대 위치가 기본적으로 첫 번째 상위 위치이므로 절대 위치 방법을 사용해야합니다. 이렇게 :

<!-- CENTERED USING MARGIN -->
<div style="width:300px; height:100px; border: 1px solid #000; margin:20px auto; text- align:center;">
    <p style="line-height:4;">width: 300 px; margin: 0 auto</p>
    <div style="position:absolute; width:100px; height:100px; background-color:#ff0000; top:-20px; left:0px;">
        <p style="line-height:4;">Absolute</p>
    </div>
</div>

<!-- CENTERED USING POSITION -->
<div style="position:absolute; left:50%; width:300px; height:100px; border: 1px solid #000; margin:20px 0 20px -150px; text-align:center;">
    <p style="line-height:2;">width:300px; position: absolute; left: 50%; margin-left:-150px;</p>
    <div style="position:absolute; width:100px; height:100px; background-color:#ff0000; top:0px; left:-105px;">
        <p style="line-height:4;">Absolute</p>
    </div>
</div>

margin : 0 자동 기술을 사용 하여이 게시물을 읽을 때까지 내 콘텐츠 왼쪽에 메뉴를 만들려면 오른쪽에 동일한 너비 열을 작성하여 균형을 맞췄습니다. 예쁘지 않은. 감사!



-1

html, body, ul, li, img {
  box-sizing: border-box;
  margin: 0px;  
  padding: 0px;  
}

#slideshowWrapper {
  width: 25rem;
  height: auto;
  position: relative;
  
  margin-top: 50px;
  border: 3px solid black;
}

ul {
  list-style: none;
  border: 3px solid blue;  
}

li {
  /* center horizontal */
  position: relative;
  left: 0;
  top: 50%;
  width: 100%;
  text-align: center;
  font-size: 18px;
  /* center horizontal */
  
  border: 3px solid red; 
}

img {
  border: 1px solid #ccc;
  padding: 4px;
  //width: 200px;
  height: 100px;
}
<body>
  <div id="slideshowWrapper">
    <ul id="slideshow">
      <li><img src="http://via.placeholder.com/350x150" alt="Dummy 1" /></li>
      <li><img src="http://via.placeholder.com/140x100" alt="Dummy 2" /></li>
      <li><img src="http://via.placeholder.com/200x100" alt="Dummy 3" /></li>      
    </ul>
  </div>
</body>


1
이 답변에는 코드 만 있습니다. 정확하지만 코드가 OP의 질문에 대답하는 이유에 대한 설명이 첨부되어 있어야합니다. 코드는 스택 익스 치지에서 "자기 설명"이 아닙니다.
— JBH
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.