Programming

더 큰 div 안에 이미지 센터를 (세로 및 가로로) 만드는 방법

procodes 2020. 2. 22. 11:59
반응형

더 큰 div 안에 이미지 센터를 (세로 및 가로로) 만드는 방법


div 200 x 200 px가 있습니다. div의 중간에 50 x 50 픽셀 이미지를 배치하고 싶습니다.

어떻게 할 수 있습니까?

text-align: centerdiv 에 사용하여 가로로 가운데에 맞출 수 있습니다. 그러나 수직 정렬이 문제입니다.


개인적으로 div 내에 배경 이미지로 배치하고 CSS는 다음과 같습니다.

#demo {
    background: url(bg_apple_little.gif) no-repeat center center;
    height: 200px;
    width: 200px;
}

( id="demo"이미 지정 height하고 width추가 때 div를 사용한다고 가정 background하면 문제가되지 않습니다)

브라우저가 부담을 느끼게하십시오.


기존 브라우저에서 작업 (IE> = 8)

자동 여백과 함께 절대 위치는 요소를 수평 및 수직으로 중앙에 배치 할 수 있습니다. 요소 위치는 상대 위치를 사용하여 부모 요소 위치를 기반으로 할 수 있습니다. 결과보기

img {
    position: absolute;
    margin: auto;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

또 다른 방법은 tablewith 을 만드는 것 입니다 valign. 이것은 div의 높이를 알고 있는지 여부에 관계없이 작동합니다.

<div>
   <table width="100%" height="100%" align="center" valign="center">
   <tr><td>
      <img src="foo.jpg" alt="foo" />
   </td></tr>
   </table>
</div>

하지만 css가능할 때마다 항상 고수해야 합니다.


position:relative;이미지를 위해 더 큰 div를 설정하면 다음 같이하십시오.

img.classname{
   position:absolute;
   top:50%;
   left:50%;
   margin-top:-25px;
   margin-left:-25px;
}

이미지와 포함 div의 크기를 모두 알고 있기 때문에 작동합니다. 이것은 또한 당신이 라인 높이를 사용하는 것과 같은 솔루션이 포함하지 않는 div를 포함하는 div 내에 다른 아이템을 가질 수있게합니다.

편집 : 참고 ... 여백은 이미지 크기의 절반입니다.


이것은 올바르게 작동합니다 :

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

위의 경우에만 수평 중심을 제공하는 경우 이것을 시도하십시오.

.outerContainer {
   position: relative;
}

.innerContainer {
   width: 50px; //your image/element width here
   height: 50px; //your image/element height here
   overflow: auto;
   margin: auto;
   position: absolute;
   top: 0; left: 0; bottom: 0; right: 0;
}

여기에 모든 것을 집중시키는 또 다른 방법이 있습니다.

일 바이올린

HTML : (그 어느 때보다도 간단 함)

<div class="Container">
    <div class="Content"> /*this can be an img, span, or everything else*/
        I'm the Content
    </div>
</div>

CSS :

.Container
{
    text-align: center;
}

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

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

혜택

컨테이너 및 내용 높이를 알 수 없습니다.

특정 음의 여백없이 선 높이를 설정하지 않고 (여러 줄의 텍스트와 잘 작동 함) 스크립트없이 중심을 맞추는 것도 CSS 전환에 적합합니다.


이것은 조금 늦어 지지만 여기에 부모 div 내에서 요소를 세로 정렬하는 데 사용하는 솔루션이 있습니다.

이것은 컨테이너 div의 크기는 알지만 포함 된 이미지의 크기는 알 수 없을 때 유용합니다. (라이트 박스 나 이미지 회전식 메뉴로 작업 할 때 자주 발생합니다).

시도해야 할 스타일은 다음과 같습니다.

 container div
 {
   display:table-cell;
   vertical-align:middle;

   height:200px;
   width:200px;
 }

 img
 {
   /*Apply any styling here*/        
 }

Flexbox 사용 :

.outerDiv {
  display: flex;
  flex-direction: column;
  justify-content: center;  /* Centering y-axis */
  align-items :center; /* Centering x-axis */
}

위의 Valamas 및 Lepu의 답변은 알 수없는 크기 또는 CSS에 하드 코딩하지 않은 알려진 크기의 이미지를 처리하는 가장 간단한 답변이라는 것을 알았습니다. 관련없는 스타일을 제거하고, 질문에 맞게 200px로 크기를 조정하고, 너무 큰 이미지를 처리하기 위해 최대 높이 / 최대 너비를 추가하십시오.

div.image-thumbnail
{
    width: 200px;
    height: 200px;
    line-height: 200px;
    text-align: center;
}
div.image-thumbnail img
{
    vertical-align: middle;
    max-height: 200px;
    max-width: 200px;
}

div에서

style="text-align:center; line-height:200px"

수직 정렬은 가장 잘못 사용되는 CSS 스타일 중 하나입니다. td 또는 css "display : table-cell"이 아닌 요소에 대해 어떻게 예상되는지 작동하지 않습니다.

이것은 그 문제에 대한 아주 좋은 게시물입니다. http://phrogz.net/CSS/vertical-align/index.html

찾고있는 것을 달성하는 가장 일반적인 방법은 다음과 같습니다.

  • 패딩 상단 / 하단
  • 절대 위치
  • 선 높이

CSS에서 다음과 같이하십시오.

img
{

  display:table-cell;
  vertical-align:middle;
  margin:auto;
}

@sleepy 다음 속성을 사용하여 쉽게이 작업을 수행 할 수 있습니다.

#content {
  display: flex;
  align-items: center;
  width: 200px;
  height: 200px;
  border: 1px solid red;
}

#myImage {
  display: block;
  width: 50px;
  height: 50px;  
  margin: auto;
  border: 1px solid yellow;
}
<div id="content">
  <img id="myImage" src="http://blog.w3c.br/wp-content/uploads/2013/03/css31-213x300.png">
</div>

참고 문헌 : W3


일반적으로 line-height200px로 설정하겠습니다 . 일반적으로 트릭을 수행합니다.


이미지의 정확한 높이 또는 너비를 모르는 이미지 갤러리가 있는데 이미지가 포함될 div보다 작다는 것을 알고 있습니다.

컨테이너에서 줄 높이 설정을 조합 하고 이미지 요소에서 vertical-align : middle사용하여 마침내 다음 HTML 마크 업과 다음 CSS를 사용하여 FF 3.5, Safari 4.0 및 IE7.0에서 작동하도록했습니다.

HTML 마크 업

<div id="gallery">
    <div class="painting">
        <a href="Painting/Details/2">
            <img src="/Content/Images/Paintings/Thumbnail/painting_00002.jpg" />
        </a>
    </div>
    <div class="painting">
        ...
    </div>
    ...
 </div>

CSS

div.painting
{
    float:left;

    height:138px; /* fixed dimensions */
    width: 138px;

    border: solid 1px white;
    background-color:#F5F5F5;


    line-height:138px;    
    text-align:center;

}

    div.painting a img
    {
        border:none;
        vertical-align:middle;

    }

이것은 나를 위해 작동합니다 :

<body>
  <table id="table-foo">
    <tr><td>
        <img src="foo.png" /> 
    </td></tr>
  </table>
</body>
<style type="text/css">
  html, body {
    height: 100%;
  }
  #table-foo {
    width: 100%;
    height: 100%;
    text-align: center;
    vertical-align: middle;
  }
  #table-foo img {
    display: block;
    margin: 0 auto;
  }
</style>

아직 언급되지 않은 다른 방법은 Flexbox를 사용하는 것 입니다.

컨테이너에서 다음 규칙을 설정하십시오 div.

display: flex;
justify-content: center; /* align horizontal */
align-items: center; /* align vertical */

깡깡이

div {
  width: 200px;
  height: 200px;
  border: 1px solid green;
  display: flex;
  justify-content: center;
  /* align horizontal */
  align-items: center;
  /* align vertical */
}
<div>
  <img src="http://lorempixel.com/50/50/food" alt="" />
</div>

Flexbox로 시작하여 일부 기능을 확인하고 최대 브라우저 지원을위한 구문을 구할 수있는 최적의 장소는 flexybox입니다.

또한, 브라우저 지원은 요즘 꽤 좋은입니다 caniuse

display: flex및의 브라우저 간 호환성을 위해 align-items다음을 사용할 수 있습니다.

display: -webkit-box;
display: -webkit-flex;
display: -moz-box;
display: -ms-flexbox;
display: flex;
-webkit-flex-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;

우리는 이것을 사용하여 쉽게 달성 할 수 있습니다 flex. 필요가 없습니다 background-image.

<!DOCTYPE html>
<html>
<head>
   <style>
      #image-wrapper{
         width:500px;
         height:500px;
         border:1px solid #333;
         display:flex;
         justify-content:center;
         align-items:center;
      }
   </style>
</head>
<body>

<div id="image-wrapper">
<img id="myImage" src="http://blog.w3c.br/wp-content/uploads/2013/03/css31-213x300.png">
</div>

</body>
</html>


이것은 오래된 솔루션 이지만 브라우저 시장 점유율은 IE7의 성능 저하에 대해 염려하지 않으면 IE 해킹 부분이 없어도 충분할 정도로 향상되었습니다. 이것은 외부 컨테이너의 크기를 알지만 내부 이미지의 크기를 알거나 알 수 없을 때 작동합니다.

.parent {
    display: table;
    height: 200px; /* can be percentages, too, like 100% */
    width: 200px; /* can be percentages, too, like 100% */
}

.child {
    display: table-cell;
    vertical-align: middle;
    margin: 0 auto;
}
 <div class="parent">
     <div class="child">
         <img src="foo.png" alt="bar" />
     </div>
 </div>

쉬운

img {
    transform: translate(50%,50%);
}

아래 코드를 사용하여 이미지를 가로 및 세로 가운데에 배치 할 수 있습니다 (IE / FF에서 작동). 이미지의 위쪽 가장자리를 브라우저 높이의 정확히 50 %에 배치하고 margin-top (이미지 높이의 절반 높이)이 이미지의 중앙에 오도록합니다.

<style type="text/css">
    #middle {position: absolute; top: 50%;} /* for explorer only*/
    #middle[id] {vertical-align: middle; width: 100%;}
         #inner {position: relative; top: -50%} /* for explorer only */
</style>


<body style="background-color:#eeeeee">
    <div id="middle">
        <div id="inner" align="center" style="margin-top:...px"> /* the number will be half the height of your image, so for example if the height is 500px then you will put 250px for the margin-top */
            <img src="..." height="..." width="..." />
        </div>
    </div>
</body>

나는 오래된 밴드 왜건에 뛰어 드는 것을 좋아합니다!

이 답변에 대한 2015 업데이트가 있습니다. transform포지셔닝을 위해 더러운 작업을 수행하기 위해 CSS3 사용하기 시작했습니다 . 이를 통해 추가 HTML을 만들 필요가 없으며 모든 요소에서 사용할 수있는 수학 (반 너비 찾기)을 수행 할 필요가 없습니다!

여기에 예제가 있습니다 (끝에 바이올린이 있음). HTML :

<div class="bigDiv">
    <div class="smallDiv">
    </div>
</div>

CSS와 함께 :

.bigDiv {
    width:200px;
    height:200px;
    background-color:#efefef;
    position:relative;
}
.smallDiv {
    width:50px;
    height:50px;
    background-color:#cc0000;
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%, -50%);
}

내가 요즘 많이하는 것은 내가 원하는 것에 수업을주고 매번 그 수업을 재사용하는 것입니다. 예를 들면 다음과 같습니다.

<div class="bigDiv">
    <div class="smallDiv centerThis">
    </div>
</div>

CSS

.bigDiv {
    width:200px;
    height:200px;
    background-color:#efefef;
    position:relative;
}
.smallDiv {
    width:50px;
    height:50px;
    background-color:#cc0000;
}
.centerThis {
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%, -50%);
}

이렇게하면 항상 컨테이너 안에 무언가를 집중시킬 수 있습니다. 가운데에 맞추려는 것이 position정의 된 컨테이너에 있는지 확인해야합니다 .

여기 바이올린이 있습니다

BTW : SMALLER div 내부의 BIGGER div를 중심으로 작동합니다.


hmtl과 CSS를 사용하여 이미지를 원 모양 내에서 세로 및 가로로 가운데에 맞추려고했습니다.

이 스레드에서 여러 지점을 결합한 후 여기에 내가 찾은 것이 있습니다 : jsFiddle

다음은 세 개의 열 레이아웃 내의 다른 예입니다. jsFiddle

CSS :

#circle {
width: 100px;
height: 100px;
background: #A7A9AB;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px;
margin: 0 auto;
position: relative;
}

.images {
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}

HTML :

<div id="circle">
<img class="images" src="https://png.icons8.com/facebook-like-filled/ios7/50" />
</div>

이것에 의해 이미지의 위치가 중앙에 수평이되도록 설정할 수 있습니다

#imageId {
   display: block;
   margin-left: auto;
   margin-right:auto;
}

단서를위한 다른 사람에게 감사합니다.

이 방법을 사용했습니다

div.image-thumbnail
{
    width: 85px;
    height: 85px;
    line-height: 85px;
    display: inline-block;
    text-align: center;
}
div.image-thumbnail img
{
    vertical-align: middle;
}

포지셔닝을 사용하십시오. 다음은 나를 위해 일했습니다.

div{
    display:block;
    overflow:hidden;
    width: 200px; 
    height: 200px;  
    position: relative;
}
div img{
    width: 50px; 
    height: 50px;   
    top: 50%;
    left: 50%;
    bottom: 50%;
    right: 50%;
    position: absolute;
}

아래와 같이 이미지 여백 자동을 설정하십시오.

img{
 margin:auto;
 width:50%;
 height:auto;
}

예를 확인하십시오


.container {
height: 200px;
width: 200px;
float:left;
position:relative;
}
.children-with-img {
position: absolute;
width:50px;
height:50px;
left:50%;
top:50%;
transform:translate(-50%);
}

div {
  position: absolute;
  
  border: 3px solid green;
  width: 200px;
  height: 200px;
}

img { 
  position: relative;
  
  border: 3px solid red;
  width: 50px;
  height: 50px;
}

.center {    
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%); /* IE 9 */
  -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */
}
<div class="center">
  <img class="center" src="http://placeholders.org/250/000/fff" />
</div>

관련 : 이미지 중앙


이것은 나를 위해 일했습니다. 이것을 이미지 CSS에 추가하십시오 :

img
{
   display: block;
   margin: auto;
}

참고 URL : https://stackoverflow.com/questions/388180/how-to-make-an-image-center-vertically-horizontally-inside-a-bigger-div



반응형