반응 형 높이로 div 내부의 이미지를 세로로 정렬


135

브라우저의 크기를 조정할 때 너비에 따라 높이가 변하는 컨테이너를 설정하는 다음 코드가 있습니다 (제곱 종횡비 유지).

HTML

<div class="responsive-container">
    <div class="dummy"></div>
    <div class="img-container">
        <IMG HERE>
    </div>
</div>

CSS

.responsive-container {
    position: relative;
    width: 100%;
    border: 1px solid black;
}

.dummy {
    padding-top: 100%; /* forces 1:1 aspect ratio */
}

.img-container {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

컨테이너 내부에서 IMG를 수직으로 정렬하려면 어떻게해야합니까? 모든 이미지의 높이는 가변적이며 반응 형이므로 컨테이너의 높이 / 선 높이를 고정 할 수 없습니다 ... 도와주세요!


1
간단한 flexbox 솔루션은 다음과 같습니다. stackoverflow.com/a/31977476/3597276
— Michael Benjamin

답변:


381

다음은 부모 내부의 인라인 요소를 가로 및 세로로 동시에 정렬하는 기술입니다 .

수직 정렬

1) 이 방법에서는, 우리는 만들 inline-block의) 첫 번째 (또는 마지막 자식으로 (사이비) 요소 의 부모를 , 그 설정 height하는 속성을 100%자사의 모든 높이 취할 부모 .

2) 또한 추가 vertical-align: middle하면 인라인 (-블록) 요소가 줄 공간의 중간에 유지됩니다. 따라서 CSS 선언을 첫 번째 자식 요소 와 요소 ( 이미지 )에 모두 추가합니다.

3) 마지막으로 inline (-block) 요소 사이의 공백 문자를 제거하기 위해 부모 의 글꼴 크기 를 0으로 설정할 수 font-size: 0;있습니다.

참고 : 나는 Nicolas Gallagher의 이미지 교체 기술 을 다음과 같이 사용했습니다.

장점은 무엇입니까?

  • 컨테이너 ( parent )는 동적 크기를 가질 수 있습니다.
  • 이미지 요소의 크기를 명시 적으로 지정할 필요가 없습니다.

  • 이 방법을 사용 하여 <div>요소를 세로 로 정렬 할 수도 있습니다 . 동적 콘텐츠 (높이 및 / 또는 너비)를 가질 수 있습니다. 그러나 내부 텍스트를 표시하려면 의 font-size속성 을 다시 설정해야 div합니다. 온라인 데모 .

<div class="container">
    <div id="element"> ... </div>
</div>
.container {
    height: 300px;
    text-align: center;  /* align the inline(-block) elements horizontally */
    font: 0/0 a;         /* remove the gap between inline(-block) elements */
}

.container:before {    /* create a full-height inline block pseudo=element */
    content: ' ';
    display: inline-block;
    vertical-align: middle;  /* vertical alignment of the inline element */
    height: 100%;
}

#element {
    display: inline-block;
    vertical-align: middle;  /* vertical alignment of the inline element */
    font: 16px/1 Arial sans-serif;        /* <-- reset the font property */
}

출력

컨테이너에서 요소를 세로로 정렬

반응 형 컨테이너

OP는 반응 형 컨테이너를 만드는 방법을 이미 알고 있으므로이 섹션에서는 질문에 대답하지 않습니다. 그러나 어떻게 작동하는지 설명하겠습니다.

컨테이너 요소 의 높이 를 가로 / 세로 비율 과 함께 너비 에 따라 변경 하려면 top / bottom padding속성에 백분율 값을 사용할 수 있습니다 .

상단 / 하단 패딩 또는 여백 의 백분율 값 은 포함 블록의 너비를 기준으로합니다.

예를 들어 :

.responsive-container {
  width: 60%;

  padding-top: 60%;    /* 1:1 Height is the same as the width */
  padding-top: 100%;   /* width:height = 60:100 or 3:5        */
  padding-top: 45%;    /* = 60% * 3/4 , width:height =  4:3   */
  padding-top: 33.75%; /* = 60% * 9/16, width:height = 16:9   */
}

다음은 온라인 데모 입니다. 하단에서 선을 주석 처리하고 패널 크기를 조정하여 효과를 확인하십시오.

또한, 우리는 적용 할 수 paddingA와 속성을 더미 자녀 또는 :before/ :after같은 결과를 달성하기 위해 의사 요소입니다. 그러나 참고 하는 것이이 경우에 백분율 값을 padding받는 상대적인 폭 의 .responsive-container자체.

<div class="responsive-container">
  <div class="dummy"></div>
</div>
.responsive-container { width: 60%; }

.responsive-container .dummy {
  padding-top: 100%;    /*  1:1 square */
  padding-top: 75%;     /*  w:h =  4:3 */
  padding-top: 56.25%;  /*  w:h = 16:9 */
}

데모 # 1 .
데모 # 2 ( :after의사 요소 사용)

내용 추가

padding-top속성을 사용 하면 컨테이너 내부의 내용 상단 또는 하단에 큰 공간 이 생깁니다 .

그 문제를 해결하기 위해서, 우리는, 래퍼 소자에 의해 콘텐츠를 포장하여 문서 정상적인 흐름이 소자 분리가 절대 위치를 (BU는 사용 랩퍼 확장 마지막하고 top, right, bottom및 left특성)이 부모의 전체 공간을 채우기 위해, 용기 .

여기 우리는 간다 :

.responsive-container {
  width: 60%;
  position: relative;
}

.responsive-container .wrapper {
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
}

다음은 온라인 데모 입니다.


모두 함께

<div class="responsive-container">
  <div class="dummy"></div>

  <div class="img-container">
    <img src="http://placehold.it/150x150" alt="">
  </div>
</div>
.img-container {
  text-align:center; /* Align center inline elements */
  font: 0/0 a;       /* Hide the characters like spaces */
}

.img-container:before {
  content: ' ';
  display: inline-block;
  vertical-align: middle;
  height: 100%;
}

.img-container img {
  vertical-align: middle;
  display: inline-block;
}

작동하는 데모 는 다음과 같습니다 .

분명히, 브라우저 호환성을::before 위해 의사 요소를 사용하지 않고 요소를 첫 번째 하위 요소로 작성할 수 있습니다 ..img-container

<div class="img-container">
    <div class="centerer"></div>
    <img src="http://placehold.it/150x150" alt="">
</div>
.img-container .centerer {
  display: inline-block;
  vertical-align: middle;
  height: 100%;
}

업데이트 된 데모 .

max-*속성 사용

상자 안의 이미지를 더 낮은 너비로 유지하려면 이미지를 설정 max-height하고 max-width속성을 지정할 수 있습니다 .

.img-container img {
    vertical-align: middle;
    display: inline-block;
    max-height: 100%;  /* <-- Set maximum height to 100% of its parent */
    max-width: 100%;   /* <-- Set maximum width to 100% of its parent */
}

다음은 업데이트 된 데모 입니다.


1
Hi Hashem은 답변을 주셔서 감사합니다-이것은 작은 너비로 크기를 조정할 때도 데스크탑 브라우저의 마술처럼 작동했습니다. 그러나 불행히도 이미지는 모바일에서 컨테이너 div 아래의 위치에 나타나지 않습니다 (Android v2.3.5). 이 문제를 해결하기위한 아이디어가 있습니까?
— user1794295

3
@ user1794295 browserstack.com을 통해 안드로이드 v2.3 (Galaxy S II, Galaxy Note, Motorola Droid 4)이있는 3 개의 안드로이드 장치 에서이 바이올린을 테스트했습니다. 모든 것이 예상대로 작동합니다. 여기에서 결과를 찾을 수 있습니다 : browserstack.com/screenshots / ... . 스크린 샷을 제공하거나 문제를 구체적으로 테스트하십시오. 가능한 한 도와 드리겠습니다.
— Hashem Qolami

1
안녕하세요. browserstack.com/screenshots/… 스크린 샷 이 있습니다.-작은 기기 (예 : Xperia, LG Nexus 4)에서 볼 수 있듯이 이미지가 컨테이너 아래에 표시됩니다.
— user1794295

3
@HashemQolami 웹 사이트 구축을 시작한 이래 가장 놀라운 CSS입니다 :).
— Alexander Solonik

1
감사합니다 font-size: 0;!
— Johannes Liebermann

47

flexbox를 사용하면 쉽습니다.

깡깡이

이미지 컨테이너에 다음을 추가하십시오.

.img-container {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex; /* add */
    justify-content: center; /* add to align horizontal */
    align-items: center; /* add to align vertical */
}

2
이 솔루션은 효과가 있으며 제 경우에는 훨씬 우아합니다. CSS3 Flex는 대단합니다!
— Daniel Bonnell

2
Safari에서는 작동하지 않습니다 :( 문제가 유연
— 하다고

1
사파리에 대한 @yennefer -webkit-접두사를 사용 하거나 prefixfree.js와 같은 라이브러리를 사용해보십시오 :)
— QUB3X

컨테이너 높이가 반응적일 때 (%) 작동하지 않습니다.
— jenlampton

1
완벽한 솔루션!
— Nirus

16

이미 마크 업 했으므로이 CSS를 사용하십시오.

.img-container {
    position: absolute;
    top: 50%;
    left: 50%;
}

.img-container > img {
  margin-top:-50%;
  margin-left:-50%;  
}

작동하는 JSBin은 다음과 같습니다. http://jsbin.com/ihilUnI/1/edit

이 솔루션은 정사각형 이미지에만 적용됩니다 (백분율 여백 값은 높이가 아니라 컨테이너 너비에 따라 달라지기 때문에). 임의 크기 이미지의 경우 다음을 수행 할 수 있습니다.

.img-container {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%); /* add browser-prefixes */
}

작동하는 JsBin 솔루션 : http://jsbin.com/ihilUnI/2/edit


죄송합니다. 저에게는 효과가 없습니다. 이미지 크기를 컨테이너 너비의 절반으로 줄였습니다.
— user1794295

2
내가 언급 한 CSS에서 어떻게 일어날 수 있는지 알 수 없습니다. 답변을 개선 할 수 있도록 실제 샘플을 제공해주세요. 추신 : 나는 또한 다른 해결책을 제공했습니다 :)
— Tibos

11

margin: auto절대 위치를 사용하여 이미지를 가로 및 세로로 가운데에 맞출 수 있습니다 . 또한:

  1. 의사 요소를 사용하여 추가 마크 업을 버릴 수 있습니다.
  2. 음의 왼쪽, 위쪽, 오른쪽 및 아래쪽 값을 사용하여 LARGE 이미지의 중간 부분을 표시 할 수 있습니다.

.responsive-container {
  margin: 1em auto;
  min-width: 200px;       /* cap container min width */
  max-width: 500px;       /* cap container max width */
  position: relative;     
  overflow: hidden;       /* crop if image is larger than container */
  background-color: #CCC; 
}
.responsive-container:before {
  content: "";            /* using pseudo element for 1:1 ratio */
  display: block;
  padding-top: 100%;
}
.responsive-container img {
  position: absolute;
  top: -999px;            /* use sufficiently large number */
  bottom: -999px;
  left: -999px;
  right: -999px;
  margin: auto;           /* center horizontally and vertically */
}
<p>Note: images are center-cropped on &lt;400px screen width.
  <br>Open full page demo and resize browser.</p>
<div class="responsive-container">
  <img src="http://lorempixel.com/400/400/sports/9/">
</div>
<div class="responsive-container">
  <img src="http://lorempixel.com/400/200/sports/8/">
</div>
<div class="responsive-container">
  <img src="http://lorempixel.com/200/400/sports/7/">
</div>
<div class="responsive-container">
  <img src="http://lorempixel.com/200/200/sports/6/">
</div>


감사! 귀하의 .responsive-container img css는 저에게 효과적이었습니다.
— Diogo Garcia

4

이거 한번 해봐

  .responsive-container{
          display:table;
  }
  .img-container{
          display:table-cell;
          vertical-align: middle;
   }

이것이 작동하지 않아 죄송합니다. 제 .img-container위치가 절대적으로 있기 때문에 제곱 종횡비 / 동적 높이를 유지하는 데 필요합니다.
— user1794295

2

다음은 모든 컨텐츠를 세로 및 가로로 가운데에 맞출 수있는 기술입니다!

기본적으로 두 개의 컨테이너 만 있으면되고 요소가 다음 기준을 충족하는지 확인하십시오.

외부 컨테이너 :

  • 있어야한다 display: table;

내부 컨테이너 :

  • 있어야한다 display: table-cell;
  • 있어야한다 vertical-align: middle;
  • 있어야한다 text-align: center;

내용 상자 :

  • 있어야한다 display: inline-block;

이 기술을 사용하는 경우 이미지를 다른 콘텐츠와 함께 이미지 상자에 추가하십시오.

데모 :

body {
    margin : 0;
}

.outer-container {
    position : absolute;
    display: table;
    width: 100%;
    height: 100%;
    background: #ccc;
}

.inner-container {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

.centered-content {
    display: inline-block;
    background: #fff;
    padding : 12px;
    border : 1px solid #000;
}

img {
   max-width : 120px;
}
<div class="outer-container">
   <div class="inner-container">
     <div class="centered-content">
        <img src="https://i.stack.imgur.com/mRsBv.png" />
     </div>
   </div>
</div>

이 바이올린을 참조하십시오 !


2

이 솔루션을 찾기 위해이 스레드를 발견했습니다.

  • 주어진 이미지 너비의 100 %를 사용합니다.
  • 이미지 종횡비 유지
  • 이미지를 중간에 수직으로 정렬합니다
  • Flex를 완벽하게 지원하지 않는 브라우저에서 작동

위에 게시 된 솔루션 중 일부 를 테스트 하면이 기준을 모두 충족하는 솔루션을 찾지 못했기 때문에이 작업을 수행 해야하는 다른 사람들에게 유용한이 간단한 솔루션을 모았습니다.

.container {
  width: 30%;
  float: left;
  border: 1px solid turquoise;
  margin-right: 3px;
  margin-top: 3px;
}

.container:last-of-kind {
  margin-right: 0px;
}

.image-container {
  position: relative;
  overflow: hidden;
  padding-bottom: 70%;
  /* this is the desired aspect ratio */
  width: 100%;
}

.image-container img {
  position: absolute;
  /* the following 3 properties center the image on the vertical axis */
  top: 0;
  bottom: 0;
  margin: auto;
  /* uses image at 100% width (also meaning it's horizontally center) */
  width: 100%;
}
<div class="container">
  <div class="image-container">
    <img src="http://placehold.it/800x800" class="img-responsive">
  </div>
</div>

<div class="container">
  <div class="image-container">
    <img src="http://placehold.it/800x800" class="img-responsive">
  </div>
</div>

<div class="container">
  <div class="image-container">
    <img src="http://placehold.it/800x800" class="img-responsive">
  </div>
</div>

에 예를 들어 작업 JSFiddle


0

시험

HTML

<div class="responsive-container">
     <div class="img-container">
         <IMG HERE>
     </div>
</div>

CSS

.img-container {
    position: absolute;
    top: 0;
    left: 0;
height:0;
padding-bottom:100%;
}
.img-container img {
width:100%;
}

0

html 코드

<div class="image-container"> <img src=""/> </div>

CSS 코드

img
{
  position: relative;
  top: 50%;
  transform: translateY(-50%);
 }

이 코드 스 니펫은 환영하고 도움이 될 수 있지만 질문을 처리하는 방법에 대한 설명 이 포함되어 있으면 크게 향상 될 것 입니다. 그것 없이는, 당신의 대답은 교육적 가치가 훨씬 낮습니다. 당신은 지금 질문하는 사람 만이 아니라 독자들에게 질문에 대답하고 있다는 것을 기억하십시오! 제발 편집 설명을 추가하고, 제한 및 가정이 적용 무엇의 표시를 제공하는 답변을.
— Toby Speight

0

다른 div를 만들고 div 안에 'dummy'과 'img-container'를 모두 추가하십시오.

다음과 같이 HTML과 CSS를 수행하십시오.

html , body {height:100%;}
.responsive-container { height:100%; display:table; text-align:center; width:100%;}
.inner-container {display:table-cell; vertical-align:middle;}
<div class="responsive-container">
    <div class="inner-container">
		<div class="dummy">Sample</div>
		<div class="img-container">
			Image tag
		</div>
	</div>	
</div>

'응답 컨테이너'의 경우 100 % 대신 원하는 높이를 제공 할 수 있습니다.,

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.