IT story

div 안에 범위 요소를 가로로 가운데에 배치하는 방법

hot-time 2020. 7. 23. 08:03
반응형

div 안에 범위 요소를 가로로 가운데에 배치하는 방법


주변 div 안에 '웹 사이트보기'와 '프로젝트보기'라는 두 링크를 중앙에 배치하려고합니다. 누군가이 작업을 수행하기 위해해야 ​​할 일을 지적 할 수 있습니까?

JS 피들 : http://jsfiddle.net/F6R9C/

HTML

<div>
  <span>
    <a href="#" target="_blank">Visit website</a>
    <a href="#">View project</a>
  </span>
</div>

CSS

div { background:red;overflow:hidden }

span a {
    background:#222;
    color:#fff;
    display:block;
    float:left;
    margin:10px 10px 0 0;
    padding:5px 10px
}

한 가지 옵션은 <a>디스플레이 를 제공 inline-block한 다음 text-align: center;포함하는 블록에 적용 하는 것입니다 (float도 제거).

div { 
    background: red;
    overflow: hidden; 
    text-align: center;
}

span a {
    background: #222;
    color: #fff;
    display: inline-block;
    /* float:left;  remove */
    margin: 10px 10px 0 0;
    padding: 5px 10px
}

http://jsfiddle.net/Adrift/cePe3/


다른 옵션은 스팬을 제공하고 스팬 display:table;을 통해 중앙에 배치하는 것입니다.margin:0 auto;

span {
display:table;
margin:0 auto;
}

<div style="text-align:center">
    <span>Short text</span><br />
    <span>This is long text</span>
</div>

적용 inline-block을 중심으로되어야하는 요소와 적용 text-align:center상위 블록에 나를 위해 속임수를 썼는지.

<span>태그 에서도 작동 합니다.


스패 인은 다루기가 약간 까다로울 수 있습니다. 티치 스팬의 너비를 설정하면

margin: 0 auto;

to center them, but they then end up on different lines. I would suggest trying a different approach to your structure.

Here is the jsfiddle I cam e up with off the top of my head: jsFiddle

EDIT:

Adrift's answer is the easiest solution :)


I assume you want to center them on one line and not on two separate lines based on your fiddle. If that is the case, try the following css:

 div { background:red;
      overflow:hidden;
}
span { display:block;
       margin:0 auto;
       width:200px;
}
span a { padding:5px 10px;
         color:#fff;
         background:#222;
}

I removed the float since you want to center it, and then made the span surrounding the links centered by adding margin:0 auto to them. Finally, I added a static width to the span. This centers the links on one line within the red div.


setting display : flex and flex-direction: row will align the nested elements horizontally.

div {
    display: flex;
    flex-direction: row;
}

참고URL : https://stackoverflow.com/questions/16489937/how-do-i-horizontally-center-a-span-element-inside-a-div

반응형