IT TIP

css 절대 위치는 margin-left : auto margin-right : auto와 함께 작동하지 않습니다.

itqueen 2020. 11. 2. 20:10
반응형

css 절대 위치는 margin-left : auto margin-right : auto와 함께 작동하지 않습니다.


div 태그에 다음 CSS를 적용했다고 가정 해 보겠습니다.

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

margin-left 및 margin-right가 적용되지 않습니다.

그러나 친척이 있으면 잘 작동합니다.

,divtagREL {
position: relative;
margin-left: auto;  
 margin-right:auto;
}

왜 그런 겁니까? 요소를 중앙에 배치하고 싶습니다.

누군가 절대 위치에서 여백을 자동으로 설정하는 것이 작동하지 않는 이유를 설명 할 수 있습니까?


편집 :이 대답은 절대적으로 배치 된 요소를 중앙에 배치 할 수 없다고 주장하는 데 사용 margin: auto;되었지만 이것은 사실이 아닙니다. 이것이 가장 많이 찬성되고 받아 들여지는 대답이기 때문에 나는 그것을 옳게 바꾸는 것이라고 생각했습니다.

다음 CSS를 요소에 적용 할 때

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

그런 다음 요소에 고정 너비와 높이 (예 : 200px 또는 40 %)를 지정하면 요소 중앙에 배치됩니다.

여기 바이올린 효과를 보여줍니다.


나는 한 절대적 위치 요소의 중심이 트릭을 사용 . 하지만 요소의 너비를 알아야합니다.

.divtagABS {
    width: 100px;
    position: absolute;
    left: 50%;
    margin-left: -50px;
  }

기본적으로 left : 50 %를 사용한 다음 음의 여백을 사용하여 너비의 절반을 되돌립니다.


절대 요소에 너비가 있으면 아래 코드를 사용할 수 있습니다.

.divtagABS{
    width:300px;
    positon:absolute;
    left:0;
    right:0;
    margin:0 auto;
}

아래 JSFiddle 작업. 절대 위치를 사용하면 margin: 0 auto작동하지 않지만 다음과 같이 할 수 있습니다 (크기도 조정됩니다).

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

업데이트 : 작업 JSFiddle


나는 이미 이와 같은 문제가 있었고 컨테이너 (.divtagABS-container, 귀하의 경우)를 절대적으로 배치 한 다음 상대적으로 그 안에 콘텐츠를 배치하는 솔루션 (귀하의 경우 .divtagABS)을 얻었습니다.

끝난! 이제 .divtagABS의 margin-left 및 margin-right AUTO가 작동합니다.


모든 답변은 제안 된 솔루션 또는 해결 방법 일뿐입니다. 그러나 여전히 질문에 대한 답을 얻지 못했습니다. margin : auto는 position : relative에서는 작동하지만 position : absolute에서는 작동하지 않습니다.

다음 설명이 도움이되었습니다.

"절대 위치 요소에서는 여백이 거의 의미가 없습니다. 이러한 요소는 정상적인 흐름에서 제거되므로 페이지의 다른 요소를 밀어 낼 수 없습니다 . 이와 같은 여백을 사용하면 여백이 적용되는 요소의 배치에만 영향을 줄 수 있습니다. 다른 요소가 아닙니다. " http://www.justskins.com/forums/css-margins-and-absolute-82168.html


If the element is position absolutely, then it isn't relative, or in reference to any object - including the page itself. So margin: auto; can't decide where the middle is.

Its waiting to be told explicitly, using left and top where to position itself.

You can still center it programatically, using javascript or somesuch.


When you are defining styles for division which is positioned absolutely, they specifying margins are useless. Because they are no longer inside the regular DOM tree.

You can use float to do the trick.

.divtagABS {
    float: left;
    margin-left: auto;  
    margin-right:auto;
 }

참고URL : https://stackoverflow.com/questions/9998260/css-absolute-position-wont-work-with-margin-leftauto-margin-right-auto

반응형