div 마진 값이 않먹는데요 좀 알려주세요 > 자유게시판

자유게시판

div 마진 값이 않먹는데요 좀 알려주세요 정보

div 마진 값이 않먹는데요 좀 알려주세요

본문

xhtml1-transitional.dtd

<body style="width:100%;height:100%;background-color:black;">
<div id="box" style="position:relative;width:100px;height:100px;background-color:green;margin:100px auto;">
  <div id="test" style="margin-top:20px;width:50px;height:50px;background-color:red;"></div>
</div>
</body>

질문 1) 에서 #box 안의 #test 빨간색 div가  margin-top:20px를 적용되지않고있습니다.
질문2)position:relative 옵션은  #box 와 #test 중 어느 곳에 적용해야하는건지?

추천
0
  • 복사

댓글 13개

#box에 padding 값을 넣어주면 물론 #test가 떨어지지만...그 방법 말고 #test에 margin-top값을 넣어 떨어뜨리게 하는 방법은 없는 걸까요?
<body style="width:100%;height:100%;background-color:black;">
<div id="box" style="position:relative;width:100px;height:100px;background-color:green;margin:100px auto;">
  <div id="test" style="position:absolute;margin-top:20px;width:50px;height:50px;background-color:red;"></div>
</div>
</body>

바꾼건 없고 test 스타일에 포지션만 absolute 이걸로 하면 마진 적용됩니다.
#test 입장에서 상단의 기준점이 애매한 상황이네요. 현재와 같은 결과는 #test에 margin-top:20px 부분이 #box보다 위쪽으로 올라가서 #box의 마진과 중복되는 상황입니다.
http://www.w3.org/TR/CSS21/box.html#collapsing-margins


트릭으로는
1) #box 에 overflow:auto 또는 hidden
2) #box 에 border-top:1px solid transparent
3) #box 에 padding-top:1px

가장 좋은 방법은 역시 #box 에 padding-top:20px 이지 않을까 싶습니다
덧, position:relative 는 static + absolute 처럼 static 속성과 absolute 를 함께 갖습니다.
<strike>원하는 것이 무엇인지 모르겠지만, 위의 예제에서는 #box, #test 두 곳 다 relative 가 필요없는 상태로 보입니다. </strike>
고맙습니다.
 공부를해도 div,position margin 이해를 잘하지못해서...기본적인 문제에서
가끔 갈피를 못잡았습니다.
해당 예제에서 position 을 주셨는데 말씀하신 부모태그 안에서 자식 태그의 마진 부여에 대해서는 무의미한 코드인거 같네요.

position 에 대해 조금 더 알아보시면 도움 되실 거 같구요,

마진은 여러가지 특성이 있습니다. 

부모 자식간에 마진이 겹치는 것, 요소간의 간격 유지를 위한 세로 마진 겹침 현상 등인데요,

질문하신 부모 자식간에는 부모의 마진이 더 클시 큰 마진 값으로 포함이 되어져서
부모의 위아래 마진이 50, 자식 위 아래 마진이 20 이면 70이 아닌 50으로 표시 되는것이죠.

이는 마진이라 함은 기준점을 기준하여 바깥영역이기 때문에 그런것인데,
이를 해결하기 위해서는 위에 말씀하신대로 보더나 패딩값으로 기준점을 주면 해결이 됩니다.

하지만 이는 핵과 같은 해결방법으로 질문하신분이 궁금하신 부분은 아닌것 같아 다음으로 넘어가면,

마진 겹침 현상은 간단하게 float 를 주면 해결 할 수 있습니다.

<div id="box" style="width:100px;height:100px;background-color:green;margin:100px auto;">
<div id="test" style="float:left; margin-top:20px;width:10px;height:50px;background-color:red;"></div>
</div>

해당 예제 코드를 바꿔본 것인데, 자식 요소에 float:left 만을 추가하여 주었습니다.
(position 은 불필요한 코드라 삭제)

여기서 test 라는 자식 요소가 float 되어있는데 이를 감싸기 위해
부모 요소인 box 에 overflow:hidden; 이라는 속성을 주면 좀더 보완할 수 있겠네요.

<div id="box" style="overflow:hidden; width:100px;height:100px;background-color:green;margin:100px auto;">
<div id="test" style="float:left; margin-top:20px;width:100px;height:50px;background-color:red;"></div>
</div>
© SIRSOFT
현재 페이지 제일 처음으로