Как я могу выровнять текст и изображение, как это? - PullRequest
0 голосов
/ 07 июня 2019

Я очень плохо знаком с программированием на python / css / html, поэтому, пожалуйста, прости меня за такой простой вопрос!

Я пытаюсь выровнять свой текст и мое изображение так же, как это делает Dev Ed в этом уроке (с изображением справа и текстом слева): https://www.youtube.com/watch?v=C_JKlr4WKKs&t=624s

Но я так и не смог заставить его выглядеть так.

Я пробовал display: grid и его функции (не совсем уверен, правильно ли я это делал), flex и float.

Вот мой соответствующий раздел about.html:

        <div class="intro-content">
            <span class="intro-text">
                <h2>Jinyang Zhang</h2>
                <p>Hello and nice to meet you! My name is Jinyang Zhang
                    <br>
                    and currently I am a Kamiak High School student.
                    <br>
                    I am interested in software development and AI
                </p>
            </span>
            <img class="image-resize" src="{% static 'img/me.jpg' %}">
        </div>

Вот соответствующий раздел моего styles.css:

            /*image next to text*/
            .image-resize{
                width: 50vh;
                float: right;
                padding: 150px 100px 0px 0px;
                margin-right: 200px;
            }

            /*introduction text that appears*/
            .intro-text{
                width: 30%;
                padding: 100px 0px 0px 40px;
                /*top right bottom left*/
                transition: 1s all ease-in-out;
                opacity: 0;
                transform: translateY(20px);
                float: left;
            }

            /*animation for it to text to appear like the tutorial*/
            .intro-appear{
                opacity: 1;
                transform: translateY(0px);
            }

Мне также хотелось бы, чтобы он оставался в формате независимо от размера экрана

Большое спасибо за вашу помощь1

Ответы [ 2 ]

0 голосов
/ 07 июня 2019

Выровняйте изображение и абзац по горизонтали и вертикали в разделе:

Вы можете легко создать простое с помощью flex box:

codepen: https://codepen.io/ya3ya6/pen/WBqjBY

Html:

     <div class="container">
            <div class="text">
                <h2>Head</h2>
                <p>Paragraph and Paragraph</p>
            </div>
            <img class="image" src="https://images.unsplash.com/photo-1542141372-98a047557466?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=752&q=80">
        </div>

Css:

.container{
  display: flex;
  align-items: center;
  justify-content: space-around;
  width: 80%;
  margin: 0 auto;
  margin-top: 50px;
}
.container.img{
  width: 50%;
}
.intro-text{
  width: 40%;
}

также кодовая ручка без изменения структуры и анимации: https://codepen.io/ya3ya6/pen/mYZmaB

0 голосов
/ 07 июня 2019

Используйте Flexbox для макета. Это делает CSS очень простым для выравнивания подобных вещей. Вечнозеленый ресурс о flexbox: https://css -tricks.com / snippets / css / a-guide-to-flexbox / .

Я также добавил немного больше HTML-кода, в частности, добавив обертку вокруг вашего изображения, чтобы вам не приходилось беспокоиться о некоторых причудах, которые возникают при использовании изображений как гибких детей.

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

// Just for demo to add the class after it loads
const text = document.querySelector('.content-text');
setTimeout(function() {
  text.classList.add('intro-appear');
}, 1000);
* { box-sizing: border-box } /* bcuz */

/* section of content */
.intro-section {
  padding: 40px 0; /* buffer spacing above and below your content */
  background: #efefef;
}

/* content wrapper */
.intro-content {
  max-width: 1000px; /* Maximum width the content is allowed to be */
  padding: 0 30px; /* content never touches left/right edges */
  display: flex; /* this is a flexbox container now, horizontal by default */
  align-items: center; /* vertical alignment because the image & text are different heights */
  margin: 0 auto; /* center the whole content container horizontally if the screen is wide */
}

/* flex items */
.content {
  flex-grow: 1; /* take up all the space */
  max-width: 50%; /* 50/50 split layout */
  /* border: 1px solid red;  so you can see what's going on, uncomment to view */
}

/* image wrapper */
.content-image {
  display: flex; /* also a flexbox container... */
  align-items: center; /* ...so the img can be easily centered vertically... */
  justify-content: center; /* ...and horizontaly */
}

/* image, this just needs to obey the size of its wrapper now */
.content-image img {
  max-width: 100%; 
  max-height: 100%;
  width: auto;
  height: auto;
}

/* introduction text that appears */
.content-text {
  padding: 0 30px;
  text-align: center;
  opacity: 0;
  
  /*top right bottom left*/
  transition: 1s all ease-in-out;
  transform: translateY(20px);
}


/* animation for it to text to appear like the tutorial */
.intro-appear {
  opacity: 1;
  transform: translateY(0px);
}
<section class="intro-section">
  <div class="intro-content">
  
    <!-- here is the content, a flex item -->
    <div class="content content-text">
      <h2>Jinyang Zhang</h2>
      <p>Hello and nice to meet you! My name is Jinyang Zhang <br/>
        and currently I am a Kamiak High School student.<br/>
        I am interested in software development and AI</p>
    </div>
    
    <!-- here is the image wrapper, also a flex item -->
    <div class="content content-image">
      <img class="image-resize" src="https://picsum.photos/250/300" />
    </div>
    
  </div>
</section>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...