2013-05-27 1 views
0

는 다음과 같은 HTML을 감안할 때 :다른 요소가 옆에 떠있을 때 알 수없는 너비의 요소를 가로로 가운데 맞춤 할 수 있습니까?

<div id="container"> 
    <div id="left">Left</div> 
    <div id="centre">Centred</div> 
</div> 

및 CSS :

#left { 
    float: left; 
    text-align: left; 
} 

#centre { 
    text-align: center; 
} 

가 어떻게 수평을 고정 폭을 제공없이 centre 요소 의 중심을 할 수 있습니까? Here's a jsFiddle demonstrating what I have done so far.

The "left" element is on the left side. The "centred" element is centred horizontally relative to the space between the right side of the "left" element and the right side of the container. Both elements are vertically aligned.

내가 범용 솔루션을 선호 :

여기 The "left" element is on the left side. The "centred" element is centred horizontally relative to the container. Both elements are vertically aligned.

는 내가 지금까지 같이 얻을 수있는 작업은 다음과 같습니다 다음 이미지는 원하는 결과를 보여줍니다 어떤 것도 폭을 지정할 필요가 없습니다.

+0

'# centre' 요소가 shrink-to-fit 너비를 가지길 원합니다. 단어 대신에 문구 나 이미지가 있으면 어떻게됩니까? 다른 제약 조건들? –

+0

http : // jsfiddle.net/V9bNZ/2/ – DiederikEEn

+0

@MarcAudet, 나는 특별히 shrink-to-fit을 찾고 있지 않다. 나는 중첩하는 것이 겹치는 것보다는 움직이는 것이 더 좋다고 생각하지만, 겹쳐지는 것은 싫어. 문구 나 이미지와 관련해서는 범용 솔루션을 선호하지만 콘텐츠 형식과 관련된 솔루션에 관심이 있습니다. – Sam

답변

1

왼쪽 DIV의 폭을 알고 있다면, 당신은 이런 식으로 작업을 수행 할 수 있습니다

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="utf-8"> 

<style media="all"> 

#left { 
    float: left; 
    width: 30px; 
} 

#centre { 
    margin: 0 40px; 
    text-align: center; 
} 

#left, #centre, #container { 
    border: 1px solid #000; 
} 

#container { 
    width: 175px; 
    padding: 5px; 
} 

</style> 

</head> 
<body> 

<div id="container"> 
    <div id="left">Left</div> 
    <div id="centre">Centred</div> 
</div> 

</body> 
</html> 
1

당신은 콘텐츠에 대한 수축에 맞는 폭과 #centre 요소를 원하는 경우에, 당신은을 사용할 수 있습니다

<div id="container"> 
    <div id="left">Left</div> 
    <div id="centre">Centred</div> 
</div> 

을 다음과 같은 CSS : 다음 당신은 오히려 감소를 얻고 싶다면

#container { 
    width: 175px; 
    text-align: center; 
    position: relative; 
    border: 1px solid black; 
    padding: 5px; 
    margin: 5px; 
} 
#left { 
    position: absolute; 
    border: 1px solid black; 
    padding: 5px; 
    margin: 5px; 
} 

#centre { 
    display: inline-block; 
    border: 1px solid black; 
    padding: 5px; 
    margin: 5px; 
} 

너비가 #centre 인 경우 요소를 플로팅하거나 절대 위치 지정을 사용하거나 인라인 블록 표시 유형을 선언해야합니다. #centre의 너비를 지정하고 싶지 않으므로 float 또는 절대 위치 지정을 사용하면 내용을 가운데에 맞출 수 없습니다. 그러나 display: inline-block을 지정하고 #containertext-align: center을 사용하면 요소를 가운데에 배치하고 테두리, 패딩 등에 대한 스타일을 제어 할 수 있습니다.

그러나이 작업을 수행하려면 #left 요소에 절대 위치 지정을 사용해야합니다. float을 사용하면 #centre의 내용이 왼쪽 요소 주위를 둘러 싸고 가운데 맞춤을 바꿉니다.

#containerposition: relative을 설정하면 #element이 페이지의 루트 (또는 다른 정적 위치가 지정되지 않은) 요소에 대해 배치됩니다.

바이올린

: 데모 예제에서 http://jsfiddle.net/audetwebdesign/hTFBa/

각주

, 당신은 콘텐츠에 대한 하나의 단어 텍스트 레이블이 있습니다. 여러 단어로 구성된 구문이있는 경우 텍스트가 겹치지 않도록 왼쪽 요소의 너비를 제한하거나 가운데 요소에 여백을 지정해야합니다.

관련 문제