У меня есть несколько div
с image
а spam
и html:
<div style="background:red">
<img src="http://s21.postimg.org/qku195lvr/graphics_dept.jpg" width="400px" />
<span class="text">Center Text</span>
</div>
<div style="background:red">
<img src="http://s21.postimg.org/qku195lvr/graphics_dept.jpg" width="300px" />
<span class="text">Center Text</span>
</div>
<div style="background:red">
<img src="http://s21.postimg.org/qku195lvr/graphics_dept.jpg" width="500px" />
<span class="text">Center Text</span>
</div>
и jsfiddel - http://jsfiddle.net/Azb99/3/
Я пытаюсь установить <span class="text">Center Text</span>
в центр изображения, а изображение имеет динамический размер.
Я пробовал этот css:
.text {
position:relative;
top:-50%;
left:50%;
text-align:center;
background:#fff;
padding:5px;
border:1px solid #ccc;
}
как может установлен Center Text
текст центровки и середина изображения?
см. http://jsfiddle.net/Azb99/8/, чтобы помочь подробнее..
Используйте absolute
позицию вместо relative
для span
потому что relative
позиция по умолчанию.
Тогда просто играйте с position
ing :)
.text {
position:absolute;
text-align:center;
background:#fff;
left :25%;
top:50%;
padding:5px;
border:1px solid #ccc;
color:black;
}
РЕДАКТИРОВАТЬ
Чтобы показать на каждом изображении, это должна быть ваша разметка:
div{
position:relative; /* this is important as its the parent and needs to have a position*/
}
img{
width:100%; /* make image take full width*/
height:100%; /* or auto, if you want to maintain aspect ratio */
position:relative;
z-index:9; /* to show one over other, lesser z-index will be below */
}
.text {
position:absolute;
z-index:99;
text-align:center;
background:#fff;
left :50%;
top:50%;
padding:5px;
border:1px solid #ccc;
color:black;
}
EDIT 2
это ваш окончательный результат и должен вас поймать !! :)
div {
position:relative;
display:inline-block;
}
img {
position:relative;
z-index:9;
}
.text {
position:absolute;
vertical-align:middle;
z-index:99;
text-align:center;
background:#fff;
min-height:20px; /* added this */
top: calc(50% - 20px); /* added this */
width:100px; /* added this */
word-break:break-all; /* added this */
left:0;
right:0;
margin : 0 auto;
padding:5px;
border:1px solid #ccc;
color:black;
}
Легко, если вы можете установить фиксированную ширину в текстовом контейнере, таким образом, вы можете переместить ее влево для половины своей ширины:
figure {
position: relative;
display: inline-block;
}
figure img {
display: block;
}
.text {
position: absolute;
bottom: 10px;
left: 50%;
width: 50%;
margin-left: -25%;
padding: 5px;
box-sizing: border-box;
text-align: center;
background: #fff;
border: 1px solid #ccc;
}