programing

너비가 없는 디브 블록의 중심을 맞춥니다.

cafebook 2023. 9. 10. 12:38
반응형

너비가 없는 디브 블록의 중심을 맞춥니다.

div block "제품"의 중심을 잡으려고 하면 div width를 미리 몰라서 문제가 생깁니다.해결책이 있는 사람?

업데이트: 문제는 몇 개의 제품을 전시할지 모르겠다는 것입니다. 1개, 2개, 3개의 제품을 가질 수 있습니다. 고정된 번호였다면 부모 디브의 폭을 알 수 있었기 때문에 중앙에 배치할 수 있습니다. 내용이 동적일 때 어떻게 하는지 모르겠습니다.

.product_container {
  text-align: center;
  height: 150px;
}

.products {
  height: 140px;
  text-align: center;
  margin: 0 auto;
  clear: ccc both; 
}
.price {
  margin: 6px 2px;
  width: 137px;
  color: #666;
  font-size: 14pt;
  font-style: normal;
  border: 1px solid #CCC;
  background-color:	#EFEFEF;
}
<div class="product_container">
  <div class="products" id="products">
    <div id="product_15">
      <img src="/images/ecommerce/card_default.png">
      <div class="price">R$ 0,01</div>
    </div>

    <div id="product_15">
      <img src="/images/ecommerce/card_default.png">
      <div class="price">R$ 0,01</div>
    </div>   

    <div id="product_15">
      <img src="/images/ecommerce/card_default.png">
      <div class="price">R$ 0,01</div>
    </div>
  </div>
</div>

업데이트 2015년 2월 27일: 원래 답변이 계속 투표되고 있지만, 지금은 @bobince의 접근 방식을 대신 사용합니다.

.child { /* This is the item to center... */
  display: inline-block;
}
.parent { /* ...and this is its parent container. */
  text-align: center;
}

역사적 목적의 나의 원래 게시물:

이 방법을 사용해 보는 것이 방법을 사용해 보십시오.

<div class="product_container">
    <div class="outer-center">
        <div class="product inner-center">
        </div>
    </div>
    <div class="clear"/>
</div>

매칭 스타일은 다음과 같습니다.

.outer-center {
    float: right;
    right: 50%;
    position: relative;
}
.inner-center {
    float: right;
    right: -50%;
    position: relative;
}
.clear {
    clear: both;
}

JSFiddle

여기서 착안하는 것은 가운데에 두 개의 디브(외부 디브와 내부 디브)에 내용을 포함하는 것입니다.콘텐츠에 맞게 폭이 자동으로 축소되도록 두 디브를 띄웁니다.다음으로 컨테이너 중앙에 바깥쪽 디브를 오른쪽 가장자리에 놓고 상대적으로 배치합니다.마지막으로 내부 디브를 자신의 폭의 절반만큼 반대 방향으로 상대적으로 배치합니다(실제로는 외부 디브의 폭이지만 동일).궁극적으로 콘텐츠가 어떤 컨테이너 안에 있든 간에 중심을 잡게 됩니다.

"product_container"의 높이 크기를 "product_container"의 내용물에 의존하는 경우 마지막에 빈 디브가 필요할 수 있습니다.

(기본적으로 분할) 'display: block'이 있는 요소의 너비는 컨테이너의 너비에 따라 결정됩니다.블록의 너비는 내용물의 너비에 따라 결정될 수 없습니다.

(CSS 2.1에서 'float: left/right'인 블록은 제외하지만, 센터링에는 사용되지 않습니다.)

'display' 속성을 'inline-block'으로 설정하여 블록을 부모의 텍스트 정렬 속성으로 제어할 수 있는 축소/축소 개체로 전환할 수 있지만 브라우저 지원은 얼룩이 많습니다.그렇게 하려면 대부분 해킹(예: -moz-inline-stack 참조)을 사용하여 피할 수 있습니다.

다른 방법은 테이블입니다.이것은 실제로 너비를 미리 알 수 없는 열이 있는 경우에 필요할 수 있습니다.예제 코드로 무엇을 하려고 하는지 알 수 없습니다. 축소/적합 블록이 필요한 명확한 것은 없지만 제품 목록은 표로 간주될 수 있습니다.

[PS. 웹에서 글꼴 크기에 'pt'를 절대 사용하지 않습니다.고정된 크기의 텍스트가 정말 필요한 경우에는 'meta'가 더 신뢰할 수 있고, 그렇지 않은 경우에는 '%'와 같은 상대적인 단위가 더 좋습니다.그리고 "clear: ccc both" -- 오타?]

.center{
   text-align:center; 
}

.center > div{ /* N.B. child combinators don't work in IE6 or less */
   display:inline-block;
}

JSFiddle

는 는을 합니다.display: table;CSS 규칙.은 추가 에 중심을 입니다(예:을 HTML나에속을고에의다은는을예은지가(다예s은는a:을enos은ovtg의alarkrdt가text-align: center;는 다른 에, div:든인에에해적된를다고른치에re다에를hhlev된,c적d,v:해gter

HTML:

<div class="container">
  <div class="centered">This content is centered</div>
</div>

CSS:

.centered { display: table; margin: 0 auto; }

.container {
  background-color: green;
}
.centered {
  display: table;
  margin: 0 auto;
  background-color: red;
}
<div class="container">
  <div class="centered">This content is centered</div>
</div>


업데이트(2015-03-09):

오늘날의 적절한 방법은 플렉스박스 규칙을 사용하는 것입니다.브라우저 지원은 조금 더 제한적이지만(CSS 테이블 지원 vs flexbox 지원), 이 방법은 다른 많은 것들도 허용하며, 이러한 유형의 동작을 위한 전용 CSS 규칙입니다.

HTML:

<div class="container">
  <div class="centered">This content is centered</div>
</div>

CSS:

.container {
  display: flex;
  flex-direction: column; /* put this if you want to stack elements vertically */
}
.centered { margin: 0 auto; }

.container {
  display: flex;
  flex-direction: column; /* put this if you want to stack elements vertically */
  background-color: green;
}
.centered {
  margin: 0 auto;
  background-color: red;
}
<div class="container">
  <div class="centered">This content is centered</div>
</div>

고양이 가죽을 벗기는 6가지 방법:

1번 버튼: 유형에 관계없이display: block부모의 폭을 모두 가정할 겁니다(와 결합하지 않는 한)float아니면.display: flex◦) 맞아요. 나쁜 예죠.

버튼 2: 다음으로 이동display: inline-block자동(전체가 아닌) 너비로 이어집니다.그런 다음 를 사용하여 센터를 지정할 수 있습니다.text-align: center 포장 블록에어쩌면 가장 쉽고 광범위하게 호환될 수 있을지도 모릅니다. 심지어 '빈티지' 브라우저를 사용하더라도...

.wrapTwo
  text-align: center;
.two
  display: inline-block; // instantly shrinks width

버튼 3: 랩 위에 아무것도 올려놓을 필요가 없습니다.그래서 아마도 이것이 가장 우아한 해결책일 것입니다.수직으로도 작동합니다. (번역에 대한 브라우저 지원도 충분합니다(요즘은 IE9...).).

position: relative;
display: inline-block; // instantly shrinks width
left: 50%;
transform: translateX(-50%);

Btw: 또한 높이를 알 수 없는 블록을 수직으로 센터링하는 좋은 방법입니다(절대 위치 지정과 관련하여).

버튼 4: 절대 위치 설정.포장지에 충분한 높이를 예약해야 합니다. 다른 사람들은 (수정을 명확하게 하거나 암묵적으로...)

.four
  position absolute
  top 0
  left 50%
  transform translateX(-50%)
.wrapFour
  position relative // otherwise, absolute positioning will be relative to page!
  height 50px // ensure height
  background lightgreen // just a marker

버튼 5: 플로트(블록 레벨 요소도 동적 폭으로 이동) 및 상대 이동.야생에서 이런 걸 적은 없지만요.어쩌면 단점이 있을지도...

.wrapFive
  &:after // aka 'clearfix'
    content ''
    display table
    clear both

.five  
  float left
  position relative
  left 50%
  transform translateX(-50%)

업데이트: 버튼 6: 그리고 요즘에는 플렉스박스도 사용할 수 있습니다.이 스타일은 중심 개체의 래퍼에 적용됩니다.

.wrapSix
  display: flex
  justify-content: center

→ 전체 소스 코드(문법 구문)

플로트를 사용하지 않기 위해 "인라인 블록"을 결합한 보다 우아한 솔루션을 찾았습니다. 두 가지 모두입니다.아직도 중첩된 디브토가 필요해요 의미적이지는 않지만 그냥 효과는 있어요

div.outer{
    display:inline-block;
    position:relative;
    left:50%;
}

div.inner{
    position:relative;
    left:-50%;
}

도움이 되길 바랍니다!

<div class="outer">
   <div class="target">
      <div class="filler">
      </div>
   </div>
</div>

.outer{
   width:100%;
   height: 100px;
}

.target{
   position: absolute;
   width: auto;
   height: 100px;
   left: 50%;
   transform: translateX(-50%);
}

.filler{
   position:relative;
   width:150px;
   height:20px;
}

위치하고 있는 , 한 으로 하는 하여 을 으로 가 을 (left: 50% ( ) 으로 50% (transform:translateX(-50%) 하지 의 를 의 의 하지 의 를 width:auto). 요소의 상대수 부모 요소의 위치는 정적, 절대적, 상대적 또는 고정적일 수 있습니다.

으로,div요소는 블록 요소로 표시되므로 너비가 100%이므로 중심을 맞추는 것은 의미가 없습니다.처럼 Arief로한은야다을가ayits,은f을u로가한y,width그러면 사용할 수 있습니다.auto을 지정할 때margin을 잡기 위해서div.

, 은 로 로 은 display: inlinea와 같은 행동을 하게 될 겁니다.span에 대신에div이 안 되는 이 요 요 이 .

이것은 순서 목록, 순서 목록 또는 순서 없는 목록과 같은 요소 또는 임의의 요소의 중심을 맞춥니다.외부 원소 등급과 함께 Div로 감싸면 내부 원소 등급을 부여할 수 있습니다.

외부 요소 클래스는 IE, 오래된 Mozilla 및 최신 브라우저를 설명합니다.

 .outerElement {
        display: -moz-inline-stack;
        display: inline-block;
        vertical-align: middle;
        zoom: 1;
        position: relative;
        left: 50%;
    }

.innerElement {
    position: relative;
    left: -50%;
} 

justice-content:center와 함께 css3 flexbox를 사용합니다.

    <div class="row">
         <div class="col" style="background:red;">content1</div>
          <div class="col" style="">content2</div>
    </div>


.row {
    display: flex; /* equal height of the children */
    height:100px;
    border:1px solid red;
    width: 400px;
    justify-content:center;
}

Mike M에 약간의 변화가 있습니다. 린의 대답

overflow: auto;(또는hidden ~ )로div.product_container 가 요 요 가 div.clear.

이 글은 이 글에서 따온 것입니다 -> http://www.quirksmode.org/css/clearing.html

다음은 수정된 HTML입니다.

<div class="product_container">
    <div class="outer-center">
        <div class="product inner-center">
        </div>
    </div>
</div>

여기 수정된 CSS가 있습니다.

.product_container {
  overflow: auto;
  /* width property only required if you want to support IE6 */
  width: 100%;
}

.outer-center {
  float: right;
  right: 50%;
  position: relative;
}

.inner-center {
  float: right;
  right: -50%;
  position: relative;
}

그 이유는, 없는 게 더 나은 이유는.div.clear(빈 요소가 있는 것이 잘못되었다고 느끼는 부분을 제외하고) Firefox의 과도한 마진 할당입니다.

예를 들어 다음과 같은 html이 있는 경우:

<div class="product_container">
    <div class="outer-center">
        <div class="product inner-center">
        </div>
    </div>
    <div style="clear: both;"></div>
</div>
<p style="margin-top: 11px;">Some text</p>

Firefox0에서 Firefox( 의 8.0) 을 에서 의 을 에서 11px의 여백 product_container잘 수 입니다. 더 나쁜 것은 콘텐츠가 화면 치수에 잘 맞더라도 전체 페이지에 수직 스크롤 막대를 얻을 수 있다는 점입니다.

이 새로운 CSS와 마크업을 사용해 보십시오.

다음은 수정된 HTML입니다.

<div class="product_container">
<div class="products" id="products">
   <div id="product_15" class="products_box">
       <img src="/images/ecommerce/card_default.png">
       <div class="price">R$ 0,01</div>
   </div>
   <div id="product_15" class="products_box">
       <img src="/images/ecommerce/card_default.png">
       <div class="price">R$ 0,01</div>
   </div>   
   <div id="product_15" class="products_box">
       <img src="/images/ecommerce/card_default.png">
       <div class="price">R$ 0,01</div>
   </div>
</div>

여기 수정된 CSS가 있습니다.

<pre>
.product_container 
 {
 text-align:    center;
 height:        150px;
 }

.products {
    left: 50%;
height:35px;
float:left;
position: relative;
margin: 0 auto;
width:auto;
}
.products .products_box
{
width:auto;
height:auto;
float:left;
  right: 50%;
  position: relative;
}
.price {
    margin:        6px 2px;
    width:         137px;
    color:         #666;
    font-size:     14pt;
    font-style:    normal;
    border:        1px solid #CCC;
    background-color:   #EFEFEF;
}

<div class="product_container">
<div class="outer-center">
<div class="product inner-center">
    </div>
</div>
<div class="clear"></div>
</div>

.outer-center
{
float: right;
right: 50%;
position: relative;
}
.inner-center 
{
float: right;
right: -50%;
position: relative;
}
.clear 
{
clear: both;
}

.product_container
{
overflow:hidden;
}

.product_container"에 대해 "overflow:hidden"을 제공하지 않으면 "outter-center" div는 오른쪽에 인접한 다른 컨텐츠와 겹칩니다."외부 중심" 오른쪽에 있는 링크나 버튼은 작동하지 않습니다."overflow : hidden"의 필요성을 이해하려면 "outer-center"의 배경색을 시도해 보십시오.

재미있는 해결책을 찾았습니다. 슬라이더를 만들고 있었고 슬라이드 컨트롤의 중심을 잡아야 했고 이 작업을 잘 수행했습니다.부모 위치에 상대 위치를 추가하고 자식 위치를 수직으로 이동할 수도 있습니다.http://jsfiddle.net/bergb/6DvJz/ 에서 만나보세요.

CSS:

#parent{
        width:600px;
        height:400px;
        background:#ffcc00;
        text-align:center;
    }

#child{
        display:inline-block;
        margin:0 auto;
        background:#fff;
    }  

HTML:

<div id="parent">
    <div id="child">voila</div>
</div>

display:table;그리고 세트margin로.auto

중요한 코드 비트:

.relatedProducts {
    display: table;
    margin-left: auto;
    margin-right: auto;
}

지금 몇 개의 요소가 있어도 중앙에 자동으로 정렬됩니다.

코드 조각의 예:

.relatedProducts {
    display: table;
    margin-left: auto;
    margin-right: auto;
}
a {
  text-decoration:none;
}
<div class="row relatedProducts">
<div class="homeContentTitle" style="margin: 100px auto 35px; width: 250px">Similar Products</div>
					
<a href="#">test1 </a>
<a href="#">test2 </a>
<a href="#">test3 </a>
</div>

유감스럽게도 폭을 명시적으로 지정하지 않고 이를 수행할 수 있는 유일한 방법은 (gasp) 테이블을 사용하는 것입니다.

엉망진창으로 고쳐놨는데, 효과가 있네요...

CSS:

#mainContent {
    position:absolute;
    width:600px;
    background:#FFFF99;
}

#sidebar {
    float:left;
    margin-left:610px;
    max-width:300;
    background:#FFCCCC;
}
#sidebar{


    text-align:center;
}

HTML:

<center>
<table border="0" cellspacing="0">
  <tr>
    <td>
<div id="mainContent">
1<br/>
<br/>
123<br/>
123<br/>
123<br/>
</div><div id="sidebar"><br/>
</div></td>
</tr>
</table>
</center>

이전 브라우저에서 작동하는 간단한 수정(테이블을 사용하므로 높이를 설정해야 함):

<div style="width:100%;height:40px;position:absolute;top:50%;margin-top:-20px;">
  <table style="width:100%"><tr><td align="center">
    In the middle
  </td></tr></table>
</div>
<style type="text/css">
.container_box{
    text-align:center
}
.content{
    padding:10px;
    background:#ff0000;
    color:#ffffff;

}

이너 디브 대신 스패니스트를 사용합니다.

<div class="container_box">
   <span class="content">Hello</span>
</div>

이 질문이 오래된 것은 알지만, 저는 그것을 시도하고 있습니다.보빈스의 답변과 매우 비슷하지만 작동 코드 예시가 있습니다.

각 제품을 인라인 블록으로 만듭니다.용기의 내용물 가운데를 맞춥니다.다 했어요.

http://jsfiddle.net/rgbk/6Z2Re/

<style>
.products{
    text-align:center;
}

.product{
    display:inline-block;
    text-align:left;

    background-image: url('http://www.color.co.uk/wp-content/uploads/2013/11/New_Product.jpg');
    background-size:25px;
    padding-left:25px;
    background-position:0 50%;
    background-repeat:no-repeat;
}

.price {
    margin:        6px 2px;
    width:         137px;
    color:         #666;
    font-size:     14pt;
    font-style:    normal;
    border:        1px solid #CCC;
    background-color:   #EFEFEF;
}
</style>


<div class="products">
    <div class="product">
        <div class="price">R$ 0,01</div>
    </div>
    <div class="product">
        <div class="price">R$ 0,01</div>
    </div>
    <div class="product">
        <div class="price">R$ 0,01</div>
    </div>
    <div class="product">
        <div class="price">R$ 0,01</div>
    </div>
    <div class="product">
        <div class="price">R$ 0,01</div>
    </div>
    <div class="product">
        <div class="price">R$ 0,01</div>
    </div>
</div>

참고 항목:CSS에서 동적 너비의 중앙 인라인 블록

이것은 요소의 내부 폭을 알 수 없는 div 내의 모든 것의 중심을 맞추는 한 가지 방법입니다.

#product_15{
    position: relative;
    margin: 0 auto;
    display: table;
}
.price, img{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

해결책은 다음과 같습니다.

.parent {
    display: flex;
    flex-wrap: wrap;
}

.product {
    width: 240px;
    margin-left: auto;
    height: 127px;
    margin-right: auto;
}

이 css를 product_cs 클래스에 추가합니다.

    margin: 0px auto;
    padding: 0px;
    border:0;
    width: 700px;

언급URL : https://stackoverflow.com/questions/283961/centering-a-div-block-without-the-width

반응형