Центрировать изображение внутри одного из двух столбцов с помощью CSS - PullRequest
0 голосов
/ 23 января 2019

Итак, я пытаюсь центрировать свое изображение внутри одного из двух моих столбцов. В данном случае это левый столбец. Возьмите изображение ниже, например.

enter image description here

Я получил некоторый текст во втором столбце, но изображение в первом столбце выглядит не по центру, как я это себе представляю. Вот как это выглядит сейчас.

enter image description here

Красный кружок - это то место, где я хочу, чтобы моя фотография была на самом деле.

Вот мой код

/* Regular Desktop View */

h1 {
  display: none;
}

img {
  width: 170px;
  height: 170px;
  border-radius: 50%;
  text-align: center;
}

h2 {
  text-align: left;
  margin-top: 30px;
}

p {
  margin-right: 50px;
}


/* Create two equal columns that floats next to each other */

.column {
  float: left;
  width: 50%;
  padding: 15px;
}


/* Clear floats after the columns */

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


/* End regular Desktop View */


/* Tablet/Smartphone view begins */

@media screen and (max-width: 768px) {
  img {
    width: 170px;
    height: 170px;
    display: block;
    margin-left: auto;
    margin-right: auto;
  }
  h1 {
    display: block;
    font-family: sans-serif, arial, verdana, lucida;
  }
  h2 {
    text-align: center;
  }
  p {
    width: 100%;
    padding: 10px;
  }
  /* Home Page */
  .column {
    width: 100%;
  }
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Homepage</title>
  <link rel="stylesheet" type="text/css" href="main.css">

  <style>
    /* Regular Desktop View */
    
    h1 {
      display: none;
    }
    
    img {
      width: 170px;
      height: 170px;
      border-radius: 50%;
      text-align: center;
    }
    
    h2 {
      text-align: left;
      margin-top: 30px;
    }
    
    p {
      margin-right: 50px;
    }
    /* Create two equal columns that floats next to each other */
    
    .column {
      float: left;
      width: 50%;
      padding: 15px;
    }
    /* Clear floats after the columns */
    
    .row:after {
      content: "";
      display: table;
      clear: both;
    }
    /* End regular Desktop View */
    /* Tablet/Smartphone view begins */
    
    @media screen and (max-width: 768px) {
      img {
        width: 170px;
        height: 170px;
        display: block;
        margin-left: auto;
        margin-right: auto;
      }
      h1 {
        display: block;
        font-family: sans-serif, arial, verdana, lucida;
      }
      h2 {
        text-align: center;
      }
      p {
        width: 100%;
        padding: 10px;
      }
      /* Home Page */
      .column {
        width: 100%;
      }
    }
  </style>


</head>

<body>

  <ul class="topnav">
    <label for="toggle">&#9776;</label>
    <input type="checkbox" id="toggle">
    <div class="menu">
      <li><a href="index.html" class="active">Home</a>
        <li><a href="about.html">About</a></li>
        <li><a href="portfolio.html">Portfolio</a></li>
        <li><a href="gallery.html">Gallery</a></li>
        <li><a href="contact.html">Contact Me</a></li>
    </div>
  </ul>

  <h1 align="center">HOME</h1>


  <div class="row">

    <div class="column">
      <img src="img/image1.jpg" class="float-center">
    </div>

    <div class="column">
      <h2>This is an h2 Title</h2>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet pretium urna. Vivamus venenatis velit nec neque ultricies, eget elementum magna tristique. Quisque vehicula, risus eget aliquam placerat, purus leo tincidunt eros, eget luctus
        quam orci in velit. Praesent scelerisque tortor sed accumsan convallis.
      </p>
    </div>

  </div>

</body>

</html>

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

Ответы [ 2 ]

0 голосов
/ 23 января 2019

Вот каков был мой план ( в эскизе ).С рабочего стола на мобильный.

enter image description here

enter image description here

Мне удалось задать правильный вопрос вдругой форум, и я получил этот ответ.

HTML

<div class="parent">

  <div class="image">
    <img src="https://i.redd.it/q2iv8opn50kz.jpg" style="width: 170px; height: 170px; border-radius:50%;">
  </div>

  <div class="text">
    <h2>This is an h2 tag</h2>
    <p>
      The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions
      from the 1914 translation by H. Rackham.
    </p>
  </div>

</div>

CSS

.parent {
  display: flex; /* Where the mobile part begins */
  justify-content: center;
  text-align: center;
  flex-wrap: wrap;
  padding: 50px 0 0 30px;
}

.parent div {
  height: 200px;
  width: 300px;
}

img {
  width: 170px;
  height: 170px;
}

Теперь у меня есть две «колонки», это работает!

0 голосов
/ 23 января 2019

Поскольку по умолчанию тег <img> в HTML5 является элементом inline-block, вы можете отцентрировать его, применив к нему text-align: center;. Это может показаться не интуитивно понятным, так как говорит от центра текста до центра , но на самом деле это относится ко всему контенту типа inline-block.

Найдите ниже обновленный фрагмент с новым классом .centered, который был добавлен в первый столбец, так что центрируется только его содержимое.

/* Regular Desktop View */

h1 {
  display: none;
}

img {
  width: 170px;
  height: 170px;
  border-radius: 50%;
  text-align: center;
}

h2 {
  text-align: left;
  margin-top: 30px;
}

p {
  margin-right: 50px;
}


/* Create two equal columns that floats next to each other */

.column {
  float: left;
  width: 50%;
  padding: 15px;
}

.centered {
  text-align: center;
}

/* Clear floats after the columns */

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


/* End regular Desktop View */


/* Tablet/Smartphone view begins */

@media screen and (max-width: 768px) {
  img {
    width: 170px;
    height: 170px;
    display: block;
    margin-left: auto;
    margin-right: auto;
  }
  h1 {
    display: block;
    font-family: sans-serif, arial, verdana, lucida;
  }
  h2 {
    text-align: center;
  }
  p {
    width: 100%;
    padding: 10px;
  }
  /* Home Page */
  .column {
    width: 100%;
  }
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Homepage</title>
  <link rel="stylesheet" type="text/css" href="main.css">

  <style>
    /* Regular Desktop View */
    
    h1 {
      display: none;
    }
    
    img {
      width: 170px;
      height: 170px;
      border-radius: 50%;
      text-align: center;
    }
    
    h2 {
      text-align: left;
      margin-top: 30px;
    }
    
    p {
      margin-right: 50px;
    }
    /* Create two equal columns that floats next to each other */
    
    .column {
      float: left;
      width: 50%;
      padding: 15px;
    }
    /* Clear floats after the columns */
    
    .row:after {
      content: "";
      display: table;
      clear: both;
    }
    /* End regular Desktop View */
    /* Tablet/Smartphone view begins */
    
    @media screen and (max-width: 768px) {
      img {
        width: 170px;
        height: 170px;
        display: block;
        margin-left: auto;
        margin-right: auto;
      }
      h1 {
        display: block;
        font-family: sans-serif, arial, verdana, lucida;
      }
      h2 {
        text-align: center;
      }
      p {
        width: 100%;
        padding: 10px;
      }
      /* Home Page */
      .column {
        width: 100%;
      }
    }
  </style>


</head>

<body>

  <ul class="topnav">
    <label for="toggle">&#9776;</label>
    <input type="checkbox" id="toggle">
    <div class="menu">
      <li><a href="index.html" class="active">Home</a>
        <li><a href="about.html">About</a></li>
        <li><a href="portfolio.html">Portfolio</a></li>
        <li><a href="gallery.html">Gallery</a></li>
        <li><a href="contact.html">Contact Me</a></li>
    </div>
  </ul>

  <h1 align="center">HOME</h1>


  <div class="row">

    <div class="column centered">
      <img src="img/image1.jpg" class="float-center">
    </div>

    <div class="column">
      <h2>This is an h2 Title</h2>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet pretium urna. Vivamus venenatis velit nec neque ultricies, eget elementum magna tristique. Quisque vehicula, risus eget aliquam placerat, purus leo tincidunt eros, eget luctus
        quam orci in velit. Praesent scelerisque tortor sed accumsan convallis.
      </p>
    </div>

  </div>

</body>

</html>

Хороший совет на будущее заключается в том, чтобы отделить HTML от стилей CSS - постарайтесь использовать как можно меньше (если не вообще) встроенных стилей и тегов <style> в своем HTML и ссылаться на свои таблицы стилей с помощью тегов <link> , Узнайте больше об этом из этого учебника W3Schools .

...