Центрирование текста alt в галерее JS

#javascript #html #css #image-gallery #alt

#javascript #HTML #css #изображение-галерея #alt

Вопрос:

У меня есть галерея изображений, которая открывает каждое изображение под сеткой изображений в виде увеличения с описательным текстом. Кажется, я не могу расположить текст по центру и остаться на изображении. Я пытался изменить CSS с помощью overflow, width и т.д., Но я думаю, что это в коде JS. Я не знаю JS, я нашел код в codepen и внес необходимые изменения (и с некоторой помощью stack overflow!). Кроме того, я хотел бы, чтобы увеличенное изображение закрывалось и возвращалось обратно в галерею через определенный промежуток времени. Возможно ли это?

Ссылка на мой codepen https://codepen.io/Ovimel/pen/YgzVeg На первом изображении показана проблема, с которой я столкнулся.

Я новичок в программировании, и я не уверен, что разместил здесь код правильно. На самом деле, я знаю, что это неправильно, поскольку изображения не выровнены, а стандартные размеры и увеличения не загружаются, но нужно ли мне публиковать все? В codepen вы увидите, что это действительно работает / не работает. Заранее спасибо за вашу помощь!

 /*styling for gallery page images*/

* {
  box-sizing: border-box;
}


/*The grid: Four equal columns that floats next to each other */

.column {
  float: left;
  width: 25%;
  padding: 10px;
  height: 200px;
  overflow: hidden;
}


/*Style the images inside the grid */

.column img {
  opacity: 0.8;
  cursor: pointer;
  max-width: 100%;
}

.column img:hover {
  opacity: 1;
}


/* Clear floats after the columns */

.row:after {
  content: "";
  display: table;
  clear: both;
}


/* The expanding image container */

.container-gallerypage {
  position: relative;
  display: none;
  padding: 15px;
  text-align: center;
}


/* Expanding image text */

#imgtext {
  position: absolute;
  bottom: 35px;
  color: red;
  font-size: 20px;
  text-align: center;
}


/* Closable button inside the expanded image */

.closebtn {
  position: absolute;
  top: 10px;
  right: 15px;
  color: white;
  font-size: 35px;
  cursor: pointer;
}


/*styling for footer and footer text links*/

footer {
  background-color: #6e6b5c;
  color: white;
  font-family: "Days One", sans-serif;
  font-size: .8em;
  text-align: center;
  padding: 10px;
  border: solid 3px #194a76;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
}


/*@media only screen and (max-width: 320px) {
  .footer {
    background-image: url(https://kehilalinks.jewishgen.org/images/KehilaLinksLogo.transparent.png);
  }
}*/

a.footerlinks {
  color: white;
  font-weight: 600;
  text-decoration: none;
}

a.footerlinks:link,
a.footerlinks:visited {
  color: white;
}

a.footerlinks:hover,
a.footerlinks:active {
  color: #194a76;
  text-decoration: underline;
}  
 <article role="main">
  <header>
    <h1>THE GALLERY</h1>
    <p style="font-style: italic; text-align: center;">Click on an image to read the caption and to view a larger version below.</p>
  </header>


  <!-- slide gallery -->
  <!-- The four columns -->

  <div class="row">
    <div class="column">
      <img src="https://kehilalinks.jewishgen.org/Stavishche/images/20.jpg" alt="The Eli Lechtzer Family, circa 1915. (L - R, seated) Chana Butzarsky Lechtzer, Raizel (Rose) Lechtzer, Eli Lechtzer, and Golda Lechtzer (standing). If there is lots of text for an image how do I keep it within the image or have it offset to the right side and keep the image on the left side. If there is lots of text for an image how do I keep it within the image or have it offset to the right side and keep the image on the left side.
    " style="width:100%" onclick="myFunction(this);">
    </div>
    <div class="column">
      <img src="https://kehilalinks.jewishgen.org/Stavishche/images/2.jpg" alt="Sisters of Stavisht" style="width:100%" onclick="myFunction(this);">
    </div>
    <div class="column">
      <img src="https://kehilalinks.jewishgen.org/Stavishche/images/6.jpg" alt="Four girls" style="width:100%" onclick="myFunction(this);">
    </div>
    <div class="column">
      <img src="https://kehilalinks.jewishgen.org/Stavishche/images/22.jpg" alt="Raizel Lechtzer,  circa 1917. Raizel, wearing her school uniform, is about 7 years old in this photo." style="width:100%" onclick="myFunction(this);">
    </div>
  </div>

  <div class="row">
    <div class="column">
      <img src="https://kehilalinks.jewishgen.org/Stavishche/images/20.jpg" alt="The Eli Lechtzer Family, circa 1915. (L - R, seated) Chana Butzarsky Lechtzer, Raizel (Rose) Lechtzer, Eli Lechtzer, and Golda Lechtzer (standing). 
    " style="width:100%" onclick="myFunction(this);">
    </div>
    <div class="column">
      <img src="https://kehilalinks.jewishgen.org/Stavishche/images/2.jpg" alt="Sisters of Stavisht" style="width:100%" onclick="myFunction(this);">
    </div>
    <div class="column">
      <img src="https://kehilalinks.jewishgen.org/Stavishche/images/6.jpg" alt="Four girls" style="width:100%" onclick="myFunction(this);">
    </div>
    <div class="column">
      <img src="https://kehilalinks.jewishgen.org/Stavishche/images/22.jpg" alt="Raizel Lechtzer,  circa 1917. Raizel, wearing her school uniform, is about 7 years old in this photo." style="width:100%" onclick="myFunction(this);">
    </div>
  </div>


  <div class="container-gallerypage">
    <span onclick="this.parentElement.style.display='none'" class="closebtn">amp;times;</span>
    <img id="expandedImg" style="width:80%">
    <div id="imgtext" style="text-align: center;width:100%;"></div>
  </div>

</article>

<br>

<!-- Footer -->
<footer id="footerlogo" role="contentinfo">
  <p>This site is hosted at no cost to the public by
    <a class="footerlinks" href="https://jewishgen.org">JewishGen, Inc.</a>, a non-profit corporation. If you feel there is a benefit to you in accessing this site, please consider supporting our important work through
    <a class="footerlinks" href="https://jewishgen.org/JewishGen-erosity">JewishGen-erosity</a>. Visit the
    <a class="footerlinks" href="https://kehilalinks.jewishgen.org">JewishGen KehilaLinks</a> website to discover other communities.</p>
  <p>Copyright amp;copy;2012-2019. All rights reserved. Design and website by Vivian Linderman.
    <address>
            <a class="footerlinks" href="mailto:vivian_lbdn@hotmail.com">CONTACT WEBMASTER</a>
          </address>Created 2012, updated 2019.
  </p>
</footer>
</div>  

Ответ №1:

Лично я бы начал все сначала, но добавление этого в ваш CSS должно помочь

 #imgtext {
    width: 70%;
    display: block;
    margin: auto;
    position: relative;
    bottom: 100px;
}
  

Я только что протестировал в code pen, и для этого требуется тег !important

 #imgtext {
    width: 70%!important;
    display: block!important;
    margin: auto!important;
    position: relative!important;
    bottom: 100px!important;
}
  

Комментарии:

1. Это определенно работает для центрирования текста, но более длинный текст по-прежнему занимает нижнюю часть фотографии. Я изменил нижний размер: 100px; на 200px;, что исправило это для более длинного текста, но затем для изображений, в которых было несколько слов, текст был поднят слишком высоко. Кроме того, на экранах меньшего размера текст переливается в нижней части изображений. Я поиграл с полями, позицией и нижней частью безрезультатно.

Ответ №2:

Небольшая настройка вашего css может дать желаемый результат. Установите max-width (более узкий, чем полная ширина) и поле, которые будут устанавливать его соответствующим образом (в данном случае я задал ему максимальную ширину 75% и поля слева и справа по 10% [приблизительное значение, с учетом добавленных браузером полей / отступов], и установите его равным display:block с position:absolute , 20% сверху. Любое из этих значений можно изменить по своему усмотрению, но вы получите картинку. Я бы рекомендовал использовать меньший размер шрифта в интересах меньших экранов, кстати

Надеюсь, это поможет

 //Make older browsers aware of new HTML5 layout tags 
'header nav aside article footer section'.replace(/w /g, function(n) {
  document.createElement(n)
})

function myFunction(imgs) {
  var expandImg = document.getElementById("expandedImg");
  var imgText = document.getElementById("imgtext");
  expandImg.src = imgs.src;
  imgText.innerHTML = imgs.alt;
  expandImg.parentElement.style.display = "block";
}  
 /*styling for gallery page images*/

* {
  box-sizing: border-box;
}


/*The grid: Four equal columns that floats next to each other */

.column {
  float: left;
  width: 25%;
  padding: 10px;
  height: 200px;
  overflow: hidden;
}


/*Style the images inside the grid */

.column img {
  opacity: 0.8;
  cursor: pointer;
  max-width: 100%;
}

.column img:hover {
  opacity: 1;
}


/* Clear floats after the columns */

.row:after {
  content: "";
  display: table;
  clear: both;
}


/* The expanding image container */

.container-gallerypage {
  position: relative;
  display: none;
  padding: 15px;
  text-align: center;
}


/* Expanding image text */

#imgtext {
  display: block;
  max-width:75%;
  position: absolute;
  top:20%;
  text-align:center;
  margin:0 10%;
  color: red;
  font-size: 20px;
}


/* Closable button inside the expanded image */

.closebtn {
  position: absolute;
  top: 10px;
  right: 15px;
  color: white;
  font-size: 35px;
  cursor: pointer;
}


/*styling for footer and footer text links*/

footer {
  background-color: #6e6b5c;
  color: white;
  font-family: "Days One", sans-serif;
  font-size: .8em;
  text-align: center;
  padding: 10px;
  border: solid 3px #194a76;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
}


/*@media only screen and (max-width: 320px) {
  .footer {
    background-image: url(https://kehilalinks.jewishgen.org/images/KehilaLinksLogo.transparent.png);
  }
}*/

a.footerlinks {
  color: white;
  font-weight: 600;
  text-decoration: none;
}

a.footerlinks:link,
a.footerlinks:visited {
  color: white;
}

a.footerlinks:hover,
a.footerlinks:active {
  color: #194a76;
  text-decoration: underline;
}  
 <body>
<article role="main">
  <header>
    <h1>THE GALLERY</h1>
    <p style="font-style: italic; text-align: center;">Click on an image to read the caption and to view a larger version below.</p>
  </header>


  <!-- slide gallery -->
  <!-- The four columns -->

  <div class="row">
    <div class="column">
      <img src="https://kehilalinks.jewishgen.org/Stavishche/images/20.jpg" alt="The Eli Lechtzer Family, circa 1915. (L - R, seated) Chana Butzarsky Lechtzer, Raizel (Rose) Lechtzer, Eli Lechtzer, and Golda Lechtzer (standing). If there is lots of text for an image how do I keep it within the image or have it offset to the right side and keep the image on the left side. If there is lots of text for an image how do I keep it within the image or have it offset to the right side and keep the image on the left side.
    " style="width:100%" onclick="myFunction(this);">
    </div>
    <div class="column">
      <img src="https://kehilalinks.jewishgen.org/Stavishche/images/2.jpg" alt="Sisters of Stavisht" style="width:100%" onclick="myFunction(this);">
    </div>
    <div class="column">
      <img src="https://kehilalinks.jewishgen.org/Stavishche/images/6.jpg" alt="Four girls" style="width:100%" onclick="myFunction(this);">
    </div>
    <div class="column">
      <img src="https://kehilalinks.jewishgen.org/Stavishche/images/22.jpg" alt="Raizel Lechtzer,  circa 1917. Raizel, wearing her school uniform, is about 7 years old in this photo." style="width:100%" onclick="myFunction(this);">
    </div>
  </div>

  <div class="row">
    <div class="column">
      <img src="https://kehilalinks.jewishgen.org/Stavishche/images/20.jpg" alt="The Eli Lechtzer Family, circa 1915. (L - R, seated) Chana Butzarsky Lechtzer, Raizel (Rose) Lechtzer, Eli Lechtzer, and Golda Lechtzer (standing). 
    " style="width:100%" onclick="myFunction(this);">
    </div>
    <div class="column">
      <img src="https://kehilalinks.jewishgen.org/Stavishche/images/2.jpg" alt="Sisters of Stavisht" style="width:100%" onclick="myFunction(this);">
    </div>
    <div class="column">
      <img src="https://kehilalinks.jewishgen.org/Stavishche/images/6.jpg" alt="Four girls" style="width:100%" onclick="myFunction(this);">
    </div>
    <div class="column">
      <img src="https://kehilalinks.jewishgen.org/Stavishche/images/22.jpg" alt="Raizel Lechtzer,  circa 1917. Raizel, wearing her school uniform, is about 7 years old in this photo." style="width:100%" onclick="myFunction(this);">
    </div>
  </div>


  <div class="container-gallerypage">
    <span onclick="this.parentElement.style.display='none'" class="closebtn">amp;times;</span>
    <img id="expandedImg" style="width:80%">
    <div id="imgtext" style="text-align: center;width:100%;"></div>
  </div>

</article>

<br>

<!-- Footer -->
<footer id="footerlogo" role="contentinfo">
  <p>This site is hosted at no cost to the public by
    <a class="footerlinks" href="https://jewishgen.org">JewishGen, Inc.</a>, a non-profit corporation. If you feel there is a benefit to you in accessing this site, please consider supporting our important work through
    <a class="footerlinks" href="https://jewishgen.org/JewishGen-erosity">JewishGen-erosity</a>. Visit the
    <a class="footerlinks" href="https://kehilalinks.jewishgen.org">JewishGen KehilaLinks</a> website to discover other communities.</p>
  <p>Copyright amp;copy;2012-2019. All rights reserved. Design and website by Vivian Linderman.
    <address>
            <a class="footerlinks" href="mailto:vivian_lbdn@hotmail.com">CONTACT WEBMASTER</a>
          </address>Created 2012, updated 2019.
</footer>
</body>  

Комментарии:

1. Это действительно помогает центрировать текст, но, как и в другом предложении, текст переполняется, когда размер экрана меньше. Я поиграл с настройками, но мне нужно приступить к работе. Поэтому вернемся к этому позже сегодня. Я использую шрифт большого размера, потому что основная аудитория этой страницы, как правило, старше и не очень технически подкована, чтобы знать, как увеличить страницу.

2. @Ovimel Пишите мультимедийные запросы для обработки меньших размеров экрана. (Конечно, шрифт 20pt будет переполняться !!). Вы спрашивали только о центрировании текста, и это не сервис для написания кода, а просто рука помощи. Удачи

3. Спасибо @RachelGallen, я вернусь к медиа-запросам в других местах моего кода.