2017-12-10 1 views
0

에 사업부를 중심 내가 다음 HTML을 : .button-left 항상 이미지의 중심에 있어야 할 내가 달성하고자하는 어떤CSS - 세로 이미지

<div class='container'> 
    <img src="http://lorempixel.com/400/400" /> 
    <div class='button-left'><</div> 
    </div> 

는 상관없이 이미지 크기, 대신 div는 내 html 요소에 따라 배치됩니다.

이 내 CSS입니다 :

.container img { 
    position: relative; 
} 
.button-left { 
    position: absolute; 
    top: 50%; 
    background-color: red; 
} 

할까요하지 .button-left DIV 위치의 상대 위치 지정된 이미지에 따라?

당신이 라이브 데모를 시도 할 경우에 JsBin : 당신은 이미지에 컨테이너에 position: relative을 설정하지해야 https://jsbin.com/cuwaguyiza/edit?html,css,output

+0

예, 세로로 만. Horizontaly 나는 그것이 어디에 있길 원합니다 :) –

+0

'.container {display : flex; align-items : center;}'& css를 삭제하십시오. –

+0

.button-left는 케이스의 .container에있는 상위 태그에 절대적으로 배치되므로 CSS 규칙을 수정해야합니다. –

답변

1

. 또한 버튼을 위로 옮기는 것이 좋습니다. 그래서 완벽하게 중앙에 배치됩니다.

.container { 
    position: relative; 
} 

.button-left { 
    position: absolute; 
    top: 50%; 
    transform: translateY(-50%); 
} 
+0

왜'transform : translateY (-50 %);와'top : 50 % '를 사용하고 있습니까? –

+0

요소의 중심점은 왼쪽 상단 모서리에 있고 중심점에 있지 않기 때문입니다. 따라서 요소의 높이의 절반을'position : top'에서 뺍니다. 그렇지 않으면 요소가 가운데에 정렬되지 않지만 요소 높이가 아래쪽으로 옵셋됩니다. – marcobiedermann

1

사용하지 않을 때는 position을 사용하지 마십시오.

  1. 플렉스 박스.

    .container { 
     
        display: flex; 
     
        align-items: center; 
     
    }
    <div class='container'> 
     
        <img src="http://lorempixel.com/400/400"> 
     
        <div class='button-left'>Lorem</div> 
     
    </div>

  2. 라인 높이

(U 텍스트가 단선 인 경우)

.container img { 
 
    vertical-align: middle; 
 
} 
 

 
.button-left { 
 
    display: inline-block; 
 
    line-height: 400px; 
 
}
<div class='container'> 
 
    <img src="http://lorempixel.com/400/400"><!-- dont delete this comment 
 
--><div class='button-left'>Lorem</div> 
 
</div>

0
.container img { 
    position: relative; 
} 
.button-left { 
    left: 50%; 
    position: absolute; 
    top: 50%; 
    transform: translate(-50%, -50%); 
    background-color: red; 

} 

OR

,
.container img { 
    position: relative; 
    display: block; 
    margin: 0 auto; 
}