program tip

어떻게 쉽게 수평 중앙에

radiobox 2020. 9. 30. 09:12
반응형

어떻게 쉽게 수평 중앙에
CSS를 사용하십니까? [복제]


이 질문에 이미 답변이 있습니다.

<div>페이지 에서 블록 요소 를 가로로 중앙에 배치 하고 최소 너비로 설정하려고합니다. 이를 수행하는 가장 간단한 방법은 무엇입니까? <div>요소가 내 페이지의 나머지 부분과 인라인 되기를 원합니다 . 예를 들어 보겠습니다.

page text page text page text page text
page text page text page text page text
               -------
               | div |
               -------
page text page text page text page text
page text page text page text page text

a의 경우 비 고정 폭 사업부 (즉, 당신은 사업부가 차지하는 공간이 얼마나되는지 모른다).

#wrapper {
  background-color: green; /* for visualization purposes */
  text-align: center;
}
#yourdiv {
  background-color: red; /* for visualization purposes */
  display: inline-block;
}
<div id="wrapper">    
    <div id="yourdiv">Your text</div>
</div>

의 너비 #yourdiv는 동적 이라는 것을 명심하십시오 .-> 내부의 텍스트를 수용하기 위해 늘어나거나 줄어들 것입니다.

Caniuse에서 브라우저 호환성을 확인할 수 있습니다.


대부분의 브라우저에서 다음과 같이 작동합니다.

div.centre {
  width: 200px;
  display: block;
  background-color: #eee;
  margin-left: auto;
  margin-right: auto;
}
<div class="centre">Some Text</div>

IE6에서는 다른 외부를 추가해야합니다 div.

div.layout {
  text-align: center;
}

div.centre {
  text-align: left;
  width: 200px;
  background-color: #eee;
  display: block;
  margin-left: auto;
  margin-right: auto;
}
<div class="layout">
  <div class="centre">Some Text</div>
</div>


margin: 0 auto;

CK가 말한 , 최소 폭은 모든 브라우저에서 지원되지


질문의 제목과 내용이 실제로 다르기 때문에 Flexbox.

FlexboxIE8과 IE9가 완전히 파괴 될 때까지 현재 표준 솔루션을 대체 / 추가 할 것이라고 생각합니다 .)

flexbox에 대한 현재 브라우저 호환성 표 확인

단일 요소

.container {
  display: flex;
  justify-content: center;
}
<div class="container">
  <img src="http://placehold.it/100x100">
</div>

여러 요소이지만 가운데 하나만

기본 동작은 flex-direction: row모든 하위 항목을 한 줄로 정렬하는 것입니다. 로 설정 flex-direction: column하면 선이 쌓이는 데 도움이됩니다.

.container {
  display: flex;
  flex-direction: column;
}
.centered {
  align-self: center;
}
<div class="container">
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
   </p>
  <div class="centered"><img src="http://placehold.it/100x100"></div>
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
    has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. </p>
</div>


오래된 브라우저가 문제가되지 않는다면 HTML5 / CSS3을 사용하십시오. 그렇다면 polyfill을 적용하고 여전히 HTML5 / CSS3를 사용하십시오. div에 여백이나 패딩이 없다고 가정하지만 상대적으로 설명하기 쉽습니다. 코드는 다음과 같습니다.

.centered {
    position: relative;
    left: 50%;
    transform: translateX(-50%);
}

이것이하는 일은 :

  1. div컨테이너에 상대적인 위치를 지정하십시오 .
  2. 위치 div50 %에서의 좌측의 경계를 가로 용기 가로;
  3. 의 50 % 수평으로 다시 번역 의 자신의 폭 .div

이 프로세스 div는 결국 수평 중앙에 위치 할 것이라는 것을 확인하기 위해 상상하기 쉽습니다 . 보너스로 추가 비용없이 수직 중앙에 배치 할 수 있습니다 .

.centered-vertically {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

이 접근 방식의 장점은 div를 일종의 텍스트로 간주하거나 (종종 의미 상 쓸모없는) 추가 컨테이너로 래핑하거나 고정 너비를 지정하는 등 직관적이지 않은 작업을 수행 할 필요가 없다는 것입니다. 항상 가능합니다.

transform필요한 경우 공급 업체 접두사를 잊지 마십시오 .


CSS , HTML :

div.mydiv {width: 200px; margin: 0 auto}
<div class="mydiv">
    
    I am in the middle
    
</div>

다이어그램에는 인라인 요소가 아닌 블록 수준 요소 (일반적으로 div가 있음)도 표시됩니다.

내 머리 꼭대기는 min-widthFF2 + / Safari3 + / IE7 +에서 지원됩니다. hackety CSS 또는 간단한 JS를 사용하여 IE6에서 수행 할 수 있습니다.


.center {
   margin-left: auto;
   margin-right: auto;
}

최소 너비는 전역 적으로 지원되지 않지만 다음을 사용하여 구현할 수 있습니다.

.divclass {
   min-width: 200px;
}

그런 다음 div를

<div class="center divclass">stuff in here</div>

당신은 사용해야 position: relativetext-align: center부모 요소에 다음 display: inline-block당신이 센터에 원하는 자식 요소에. 이것은 모든 주요 브라우저에서 작동하는 간단한 CSS 디자인 패턴입니다. 다음은 아래의 예 또는 CodePen 예제를 확인하십시오 .

p {
  text-align: left;
}
.container {
  position: relative;
  display: block;
  text-align: center;
}
/* Style your object */

.object {
  padding: 10px;
  color: #ffffff;
  background-color: #556270;
}
.centerthis {
  display: inline-block;
}
<div class="container">

  <p>Aeroplanigera Mi Psychopathologia Subdistinctio Chirographum Intuor Sons Superbiloquentia Os Sors Sesquiseptimus Municipatio Archipresbyteratus O Conclusio Compedagogius An Maius Septentrionarius Plas Inproportionabilit Constantinopolis Particularisticus.</p>

  <span class="object centerthis">Something Centered</span>

  <p>Aeroplanigera Mi Psychopathologia Subdistinctio Chirographum Intuor Sons Superbiloquentia Os Sors Sesquiseptimus Municipatio Archipresbyteratus O Conclusio Compedagogius.</p>
</div>


margin: 0 auto대신 CSS에서 사용할 수 있습니다 .margin-left: auto; margin-right: auto;


아래 코드를 사용하면 div가 중앙에 있습니다.

.class-name {
    display:block;
    margin:0 auto;
}

9 년 후 나는 새 버전을 가져올 때라고 생각했습니다. 여기에 내가 좋아하는 두 가지 (그리고 지금은 하나)가 있습니다.

여유

로 설정 margin합니다 auto. 방향 순서가 margin: *top* *right* *bottom* *left*;또는margin: *top&bottom* *left&right*

aside{
    display: block;
    width: 50px;
    height: 100px;
    background-color: green;
    float: left;
}

article{
    height: 100px;
    margin: 0 0 0 50px; /* 50px aside width */
    background-color: grey;
}

div{
  margin: 0 auto;
  display:block;
  width: 60px;
  height: 60px;
  background-color: blue;
  color: white;
}
<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <aside>
        </aside>
        <article>           
                <div>The div</div>
        </article>
    </body>
</html>

Center : 더 이상 사용되지 않습니다. 사용하지 마십시오!

사용 <center></center>당신의 주위에 랩으로 태그를 <div></div>.

예:

aside{
    display:block;
    background-color:green;
    width: 50px;
    height: 100px;
    float: left;
}

center{
    display:block;
    background-color:grey;
    height: 100px;
    margin-left: 50px; /* Width of the aside */
}

div{
    display:block; 
    width: 60px; 
    height: 60px; 
    background-color:blue;
    color: white;
}
<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <aside>
        </aside>
        <article>
            <center>
                <div>The div</div>
            </center>
        </article>
    </body>
</html>


div의 너비를 알고 있고 고정되어 있으면 다음 CSS를 사용할 수 있습니다.

margin-left: calc(50% - 'half-of-your-div-width');

여기서 'half-of-your-div-width'는 (분명히) div 너비의 절반이어야합니다.


당신 <div>position: absolute사용해야하는 경우width: 100%;

#parent {
    width: 100%;
    text-align: center;
}

    #child {
        display: inline-block;
    }

.center {
  height: 20px;
  background-color: blue;
}

.center>div {
  margin: auto;
  background-color: green;
  width: 200px;
}
<div class="center">
  <div>You text</div>
</div>

JsFiddle


이 클래스를 CSS 파일에 추가하면 완벽하게 작동합니다.

1) 먼저 생성

<div class="center-role-form">
  <!--your div (contrent) place here-->
</div>

2) 이것을 CSS에 추가하십시오

.center-role-form {
    width: fit-content;
    text-align: center;
    margin: 1em auto;
}

여기에 적절한 대답을 추가합니다.

이 스 니펫 코드를 사용하고 맞춤 설정할 수 있습니다. 여기에서는 2 개의 자식 블록을 사용합니다. 페이지 중앙에 표시되어야합니다. 하나 또는 여러 블록을 사용할 수 있습니다.

<html>
<head>
<style>
#parent {
    width: 100%;
    border: solid 1px #aaa;
    text-align: center;
    font-size: 20px;
    letter-spacing: 35px;
    white-space: nowrap;
    line-height: 12px;
    overflow: hidden;
}

.child {
    width: 100px;
    height: 100px;
    border: solid 1px #ccc;
    display: inline-block;
    vertical-align: middle;
}
</style>
</head>

<body>

<div class="mydiv" id="parent">


<div class="child">
Block 1
</div>
<div class="child">
Block 2
</div>

</div>
</body>
</html>

HTML 파일에 다음과 같이 작성합니다.

<div class="banner">
  Center content
</div>

작성한 CSS 파일 :

.banner {
display: block;
margin: auto;
width: 100px;
height: 50px;
}

나를 위해 작동합니다.


margin-left : auto 및 margin-right : auto의 사용은 특정 상황에서 작동하지 않을 수 있습니다. 다음은 항상 작동하는 솔루션입니다. 필요한 너비를 지정하고 왼쪽 여백을 나머지 너비의 절반으로 설정합니다.

    <div style="width:80%; margin-left:calc(10%);">
        your_html
    </div>

The best response to this question is to use margin-auto but for using it you must know the width of your div in px or %.

CSS code:

div{
    width:30%;
    margin-left:auto;
    margin-right:auto;
}

I use div and span tags together with css properties such as block, cross-browser inline-block and text-align center, see my simple example

<!DOCTYPE html>
<html>
    <head>
       <title>Page Title</title>
       <style>
           .block{display:block;}
           .text-center{text-align:center;}
           .border-dashed-black{border:1px dashed black;}
           .inline-block{
                 display: -moz-inline-stack;
                 display: inline-block;
                 zoom: 1;
                 *display: inline;
            }
           .border-solid-black{border:1px solid black;}
           .text-left{text-align:left;}
        </style>
    </head>
    <body>
          <div class="block text-center border-dashed-black">
              <span class="block text-center">
                  <span class="block"> 
        <!-- The Div we want to center set any width as long as it is not more than the container-->
                      <div class="inline-block text-left border-solid-black" style="width:450px !important;">
                             jjjjjk
                      </div> 
                  </span>
              </span>
          </div>
      </body>
   </html>

Using jQuery:

$(document).ready(function() {
    $(".myElement").wrap( '<span class="myElement_container_new"></span>' ); // for IE6
    $(".myElement_container_new").css({// for IE6
        "display" : "block",
        "position" : "relative",
        "margin" : "0",
        "padding" : "0",
        "border" : "none",
        "background-color" : "transparent",
        "clear" : "both",
        "text-align" : "center"
    });
    $(".myElement").css({
        "display" : "block",
        "position" : "relative",
        "max-width" : "75%", // for example
        "margin-left" : "auto",
        "margin-right" : "auto",
        "clear" : "both",
        "text-align" : "left"
    });
});

or, if you want to center every element with class ".myElement":

$(document).ready(function() {
    $(".myElement").each(function() {
        $(this).wrap( '<span class="myElement_container_new"></span>' ); // for IE6
        $(".myElement_container_new").css({// for IE6
            "display" : "block",
            "position" : "relative",
            "margin" : "0",
            "padding" : "0",
            "border" : "none",
            "background-color" : "transparent",
            "clear" : "both",
            "text-align" : "center"
        });
        $(this).css({
            "display" : "block",
            "position" : "relative",
            "max-width" : "75%",
            "margin-left" : "auto",
            "margin-right" : "auto",
            "clear" : "both",
            "text-align" : "left"
        });
    });
});

you can use the position:relative; and then set the left and the top values:

.cenverDiv{
    position:relative;
    left:30%;
    top:0px;
}

참고URL : https://stackoverflow.com/questions/618097/how-do-you-easily-horizontally-center-a-div-using-css

반응형