programing

절대 위치 요소를 수평으로 100% 폭 디브 안에 중심을 맞추려면 어떻게 해야 합니까?

javamemo 2023. 9. 12. 19:47
반응형

절대 위치 요소를 수평으로 100% 폭 디브 안에 중심을 맞추려면 어떻게 해야 합니까?

아래 예에서,#logo절대적으로 위치하고 수평으로 중심을 잡아야 합니다.#header. 보통은 제가.margin:0 auto상대적으로 위치한 요소들에 대해 나는 여기에 갇혀있습니다.누가 길을 가르쳐 줄 수 있습니까?

JS Fiddle: http://jsfiddle.net/DeTJH/

HTML

<div id="header">
    <div id="logo"></div>
</div>

CSS

#header {
    background:black;
    height:50px;
    width:100%;
}

#logo {
    background:red;
    height:50px;
    position:absolute;
    width:50px
}

왼쪽 특성의 중심을 정렬하려면.
상단 정렬의 경우에도 마찬가지입니다. margin-top을 사용할 수 있습니다. (div의 너비/2) 개념은 왼쪽 속성과 동일합니다.
헤더 요소를 위치:relative로 설정하는 것이 중요합니다.
시도해 보십시오.

#logo {
    background:red;
    height:50px;
    position:absolute;
    width:50px;
    left:50%;
    margin-left:-25px;
}

데모

계산을 사용하지 않으려면 다음 작업을 수행할 수 있습니다.

#logo {
  background:red;
  width:50px;
  height:50px;
  position:absolute;
  left: 0;
  right: 0;
  margin: 0 auto;
}

데모2

둘 다 할당해야 합니다.left그리고.right소유물0값어치가 있는margin: auto로고의 중앙에 위치합니다.

그렇다면 이 경우:

#logo {
  background:red;
  height:50px;
  position:absolute;
  width:50px;
  left: 0;
  right: 0;
  margin: 0 auto;
}

설정할 수도 있습니다.position: relative위해서#header.

이 작업은 다음과 같이 작동합니다.left그리고.right0으로 설정하면 절대 위치의 요소가 수평으로 늘어납니다.마법은 다음과 같은 경우에 발생합니다.margin로 설정됩니다.auto.margin지정된 내용을 그대로 둔 채(각 면에 표시됨) 모든 여분의 공간을 사용합니다.width. 이로 인해 콘텐츠가 중앙 정렬됩니다.

사용이 누락되었습니다.calc더 깨끗한 해결책인 답변에서.

#logo {
  position: absolute;
  left: calc(50% - 25px);
  height: 50px;
  width: 50px;
  background: red;
}

jsFiddle

대부분의 최신 브라우저에서 작동: http://caniuse.com/calc

폴백 없이 사용하기에는 너무 이르겠지만, 미래의 방문객들에게는 도움이 될 것이라고 생각했습니다.

내 경험상 가장 좋은 방법은right:0;,left:0;그리고.margin:0 auto. 이렇게 하면 디브가 넓으면 당신은 디브의 방해를 받지 않습니다.left: 50%;음의 마진을 추가하는 결과를 초래하는 당신의 div를 상쇄할 것입니다.

데모 http://jsfiddle.net/kevinPHPkevin/DeTJH/4/

#logo {
    background:red;
    height:50px;
    position:absolute;
    width:50px;
    margin:0 auto;
    right:0;
    left:0;
}

이것은 디바 위치를 절대 중심으로 하는 가장 좋은 방법입니다.

데모 피들

코드 --

#header {
background:black;
height:90px;
width:100%;
position:relative; // you forgot this, this is very important
}

#logo {
background:red;
height:50px;
position:absolute;
width:50px;
margin: auto; // margin auto works just you need to put top left bottom right as 0
top:0;
bottom:0;
left:0;
right:0;
}

간단합니다. 이렇게 상대 상자에 포장만 하면 됩니다.

<div class="relative">
 <div class="absolute">LOGO</div>
</div>

상대 상자의 여백: 0 Auto, 그리고 중요한 것은 폭...

언급URL : https://stackoverflow.com/questions/16758102/how-do-i-horizontally-center-an-absolute-positioned-element-inside-a-100-width

반응형