[css] 내 div를 수평으로 정렬하려면 어떻게해야합니까?

어떤 이유로 내 div가 포함하는 div에서 가로로 가운데에 있지 않습니다.

.row {
  width: 100%;
  margin: 0 auto;
}
.block {
  width: 100px;
  float: left;
}
<div class="row">
  <div class="block">Lorem</div>
  <div class="block">Ipsum</div>
  <div class="block">Dolor</div>
</div>

때로는 하나의 블록 div 만있는 행 div가 있습니다. 내가 뭘 잘못하고 있죠?



답변

수행하려는 작업을 달성하려면 :

사용을 고려 display: inline-block대신 float.


답변

이 시도:

.row {
  width: 100%;
  text-align: center; // center the content of the container
}

.block {
  width: 100px;
  display: inline-block; // display inline with ability to provide width/height
}​

데모

  • 필요 margin: 0 auto;와 함께하면 width: 100%당신 요소가 전체 공간을 차지하기 때문에 쓸모가 없다.

  • float: left남은 공간이 없을 때까지 요소를 왼쪽으로 플로팅하므로 새 줄로 이동합니다. 사용은 display: inline-block인라인 요소를 표시 할 수 있지만합니다 (반대로 크기를 제공 할 수있는 능력을 가진 display: inline너비 / 높이가 무시되는 경우)


답변

CSS의 정렬은 악몽이었습니다. 운 좋게도 W3C는 2009 년에 새로운 표준 인 Flexible Box를 도입했습니다 . 여기에 좋은 튜토리얼이 있습니다 . 개인적으로 다른 방법보다 훨씬 논리적이고 이해하기 쉽습니다.

.row {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: center;
}
.block {
  width: 100px;
}
<div class="row">
  <div class="block">Lorem</div>
  <div class="block">Ipsum</div>
  <div class="block">Dolor</div>
</div>


답변

FlexBox 사용 :

<div class="row">
  <div class="block">Lorem</div>
  <div class="block">Ipsum</div>
  <div class="block">Dolor</div>
</div>

.row {
  width: 100%;
  margin: 0 auto;
  display: flex;
  justify-content: center; /* for centering 3 blocks in the center */
  /* justify-content: space-between; for space in between */
}
.block {
  width: 100px;
}

최신 트렌드는 Float를 사용하는 대신 Flex 또는 CSS Grid를 사용하는 것입니다. 그러나 여전히 일부 1 % 브라우저는 Flex를 지원하지 않습니다. 그러나 어쨌든 이전 IE 사용자를 정말로 걱정하는 사람;)

바이올린 : 여기 확인


답변

다른 작업 예 , 사용 display: inline-blocktext-align: center

HTML :

<div class='container'>
    <div class='row'>
        <div class='btn'>Hello</div>
        <div class='btn'>World</div>
    </div>
    <div class='clear'></div>
</div>

CSS :

.container {
    ...
}
.row {
    text-align: center;
}
.btn {
    display: inline-block;
    margin-right: 6px;
    background-color: #EEE;
}
.clear {
    clear: both;
}

바이올린 : http://jsfiddle.net/fNvgS/


답변

이 질문을 다루지는 않지만 ( <div>컨테이너 내부 에 s 를 정렬하고 싶기 때문에 ) 직접 관련이 있습니다. 하나의 div 만 수평으로 정렬하려면 다음을 수행 할 수 있습니다.

#MyDIV
{
    display: table;
    margin: 0 auto;
}


답변

요소가 한 줄에 표시되어야하며 IE 6/7이 문제가되지 않는 경우 사용을 고려 display: table하고 display: table-cell대신 float.

inline-block요소 사이 에 수평 간격이 생기고 그 간격을 제로화해야합니다. 가장 간단한 방법은 설정하는 font-size: 0부모 요소에 대해 다음 복원 font-size이 그 자식 요소에 대한 display: inline-block자신을 설정하여 font-sizeA를 px또는 rem값.