IT

Div의 중앙 대형 이미지

lottoking 2020. 6. 3. 08:10
반응형

Div의 중앙 대형 이미지


CSS 만 사용하여 div 내에서 대형 이미지를 중앙에 배치하는 방법을 정렬하려고했습니다.

유동적 인 레이아웃을 사용하고 있으므로 이미지 컨테이너의 너비는 페이지 너비에 따라 달라집니다 (div의 높이는 고정되어 있음). 이미지는 페이지에서 페이지를 보는 것처럼 보이도록 삽입 상자 그림자가있는 div 안에 있습니다.

이미지 자체는 가능한 가장 넓은 값 (디자인에 max-width값이 있음)으로 주변 div를 채우도록 크기가 조정되었습니다 .

이미지가 주변 div보다 작은 경우 매우 쉽습니다.

margin-left: auto;
margin-right: auto;
display: block; 

그러나 이미지가 div보다 크면 왼쪽 가장자리에서 시작하여 오른쪽 중앙에서 벗어납니다 (우리는 사용 중입니다 overflow: hidden).

우리는을 할당 할 수 width=100%있지만 브라우저는 이미지 크기를 조정하고 웹 디자인 센터는 고품질 이미지를 중심으로 거칠게 작업합니다.

이미지를 overflow:hidden중앙에 배치하여 양쪽 가장자리를 고르게 자르는 아이디어가 있습니까?


이와 같은 것을 시도하십시오. 크기에 관계없이 부모와 관련하여 세로 및 가로 가운데에 큰 요소가 가운데에 있어야합니다.

.parent {
    position: relative;
    overflow: hidden;
}

.child {
    position: absolute;
    top: -9999px;
    bottom: -9999px;
    left: -9999px;
    right: -9999px;
    margin: auto;

}

이것은 오래된 Q이지만 flexbox 또는 위치 절대가없는 현대적인 솔루션은 다음과 같이 작동합니다.

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

.outer {
  border: 1px solid green;
  margin: 20px auto;
  width: 20%;
  padding: 10px 0;
  /*   overflow: hidden; */
}

.inner {
  width: 150%;
  background-color: gold;
  /* Set left edge of inner element to 50% of the parent element */
  margin-left: 50%; 
  /* Move to the left by 50% of own width */
  transform: translateX(-50%); 
}
<div class="outer">
  <div class="inner">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos exercitationem error nemo amet cum quia eaque alias nihil, similique laboriosam enim expedita fugit neque earum et esse ad, dolores sapiente sit cumque vero odit! Ullam corrupti iure eum similique magnam voluptatum ipsam. Maxime ad cumque ut atque suscipit enim quidem. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi impedit esse modi, porro quibusdam voluptate dolores molestias, sit dolorum veritatis laudantium rem, labore et nobis ratione. Ipsum, aliquid totam repellendus non fugiat id magni voluptate, doloribus tenetur illo mollitia. Voluptatum.</div>
</div>

왜 작동합니까?
언뜻보기에 우리는 오른쪽으로 50 %, 왼쪽으로 다시 50 % 이동합니다. 그러면 제로 시프트가 발생하므로 어떻게해야합니까?
그러나 상황이 중요하기 때문에 50 %는 동일하지 않습니다. 상대 여백을 계산하는 경우 여백은 상위 요소의 백분율로 계산되는 반면 변환에서 50 %는 동일한 요소를 기준으로합니다 . 둘 다에 대한 너비입니다.

CSS를 추가하기 전에 이런 상황이 있습니다

       +-------------------------------------------+
       | Parent element P of E                     |
       |                                           |
       +-----------------------------------------------------------+
       | Element E                                                 |
       +-----------------------------------------------------------+
       |                                           |
       +-------------------------------------------+

추가 된 스타일로 margin-left: 50%우리가

       +-------------------------------------------+
       | Parent element P of E                     |
       |                                           |
       |                     +-----------------------------------------------------------+
       |                     | Element E                                                 |
       |                     +-----------------------------------------------------------+
       |                     |                     |
       +---------------------|---------------------+
       |========= a ========>|

       a is 50% width of P

그리고 transform: translateX(-50%)왼쪽으로 이동

       +-------------------------------------------+
       | Parent element P of E                     |
       |                                           |
+-----------------------------------------------------------+
| Element E                 |                               |
+-----------------------------------------------------------+
|<============ b ===========|                      |
       |                    |                      |
       +--------------------|----------------------+
       |========= a =======>|

       a is 50% width of P
       b is 50% width of E

Unfortunately this does only work for horizontal centering as the margin percentage calculation is always relative to the width. I.e. not only margin-left and margin-right, but also margin-top and margin-bottom are calculated with respect to width.

Browser compatibility should be no problem: https://caniuse.com/#feat=transforms2d


Put a large div inside the div, center that, and the center the image inside that div.

This centers it horizontally:

HTML:

<div class="imageContainer">
  <div class="imageCenterer">
    <img src="http://placekitten.com/200/200" />
  </div>
</div>

CSS:

.imageContainer {
  width: 100px;
  height: 100px;
  overflow: hidden;
  position: relative;
}
.imageCenterer {
  width: 1000px;
  position: absolute;
  left: 50%;
  top: 0;
  margin-left: -500px;
}
.imageCenterer img {
  display: block;
  margin: 0 auto;
}

Demo: http://jsfiddle.net/Guffa/L9BnL/

To center it vertically also, you can use the same for the inner div, but you would need the height of the image to place it absolutely inside it.


Late to the game, but I found this method is extremely intuitive. https://codepen.io/adamchenwei/pen/BRNxJr

CSS

.imageContainer {
  border: 1px black solid;

  width: 450px;
  height: 200px;
  overflow: hidden;
}
.imageHolder {
  border: 1px red dotted;

  height: 100%;
  display:flex;
  align-items: center;
}
.imageItself {
  height: auto;
  width: 100%;
  align-self: center;

}

HTML

<div class="imageContainer">
  <div class="imageHolder">
    <img class="imageItself" src="http://www.fiorieconfetti.com/sites/default/files/styles/product_thumbnail__300x360_/public/fiore_viola%20-%202.jpg" />
  </div>
</div>

Do not use fixed or an explicit width or height to the image tag. Instead, code it:

      max-width:100%;
      max-height:100%;

ex: http://jsfiddle.net/xwrvxser/1/


i'm a huge fan of making an image the background of a div/node -- then you can just use the background-position: center attribute to center it regardless of screen size


The width and height are only for example:

parentDiv{
    width: 100px;
    height: 100px;
    position:relative; 
}
innerDiv{
    width: 200px;
    height: 200px;
    position:absolute; 
    margin: auto;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

It has to work for you if the left and top of your parent div are not the very top and left of the window of your screen. It works for me.


I found this to be a more elegant solution, without flex:

.wrapper {
    overflow: hidden;
}
.wrapper img {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    /* height: 100%; */ /* optional */
}

참고URL : https://stackoverflow.com/questions/14562457/center-oversized-image-in-div

반응형