2017-07-09 12 views
2

ページの中央に配置された画像にテキストエリアを固定して、画面サイズが変わったときに画像から移動しないようにすることはできますか?要素を中央揃え要素にアンカーできますか?

jsfiddle上の例、及びTEXTAREAおよび画像利用 '位置:絶対' で:コンテナの使用 '相対位置' でhttps://jsfiddle.net/rxg7t2ca/1/

.container { 
 
    width: 60%; 
 
    margin: 0 auto; 
 
    /* border: 2px solid blue; */ 
 
} 
 

 
#cat { 
 
    display: block; 
 
    margin: 0 auto; 
 
} 
 

 
.box1 { 
 
    position: relative; 
 
    top: -250px; 
 
    left: 30px; 
 
    width: 100px; 
 
    height: 100px; 
 
}
<div class="container"> 
 
    <img src="http://i.imgur.com/a2Wd9D2.jpg" height=300px id="cat" /> 
 
    <textarea class="box1"> This is a text box </textarea> 
 

 
</div>

答えて

2

.container { 
 
    position: relative; 
 
    width: 60%; 
 
    margin: 0 auto; 
 
    border: 2px solid blue; 
 
} 
 

 
#cat { 
 
    width: 100%; 
 
    object-fit: cover;     /* 1 */ 
 
    vertical-align: bottom;   /* 2 */ 
 
} 
 

 
.box1 { 
 
    position: absolute;    /* 3 */ 
 
    top: 50%;       /* 3 */ 
 
    left: 50%;       /* 3 */ 
 
    transform: translate(-50%, -50%); /* 3 */ 
 
    width: 100px; 
 
    height: 100px; 
 
}
<div class="container"> 
 
    <img src="http://i.imgur.com/a2Wd9D2.jpg" height=300px id="cat" /> 
 
    <textarea class="box1"> This is a text box </textarea> 
 
</div>

説明:

  1. Why isn't object-fit working in flexbox?
  2. Mystery white space underneath image tag
  3. Element will not stay centered, especially when re-sizing screen
+1

うわあ、説明に感謝し、私は本当にソリューションとそれがどのように好きです。 – Eric

2

CSS絶対プロパティ:要素は、最初に配置された(静的ではない)祖先要素を基準にして配置されます。

.container{ 
    width: 60%; 
    margin: 0 auto; 
    position:relative; 
    /* border: 2px solid blue; */ 
} 

#cat{ 
    position: absolute; 
    top: 0px; 
    left: 0px; 
    display: block; 
    margin: 0 auto; 
} 

.box1{ 
    position: absolute; 
    top: 25px; 
    left: 30px; 
    width: 100px; 
    height: 100px; 
} 
+0

私はこれを試しましたが、画面サイズを大きくすると、指定した場所に表示されなくなります。 – Eric

+0

はい、そうです。あまりにも絶対位置を画像に使用する必要があります。 #cat {position:絶対; top:0px;左:0px;} –

+0

ああ、その作品!ありがとう男 – Eric

関連する問題