Проблемы относительного и абсолютного позиционирования

#html #css

#HTML #css

Вопрос:

Я пытаюсь позиционировать «Kipplo.co.uk «итак, он находится в центре, как кнопка, и он работает, но я хочу, чтобы дизайн был адаптивным, поэтому при изменении размера окна заголовок будет подстраиваться под него, но вместо этого он появится на панели навигации. Я также пытался использовать relative, но кнопка уже использует эту функцию.

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

(См. Прикрепленное изображение ниже)
С наилучшими пожеланиями!

https://i.stack.imgur.com/MFMpA.png

https://i.stack.imgur.com/EjjuF.png

 body {

    background-color: rgb(10, 10, 10);
}

html, body {
  max-width: 100%;
  overflow-x: hidden;
}

 /* Announcment bar */
.alert {
    padding: 20px;
    background-color: #2a7a85;
    color: white;
  }
  
  .closebtn {
    margin-left: 15px;
    color: white;
    font-weight: bold;
    float: right;
    font-size: 22px;
    line-height: 20px;
    cursor: pointer;
    transition: 0.3s;
  }
  
  .closebtn:hover {
    color: black;
  }

  body {margin: 0;}
/* Navigation bar */
  ul.topnav {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: rgb(248, 248, 248);
  }
  
  ul.topnav li {float: left;}
  
  ul.topnav li a {
    display: block;
    color: black;
    text-align: center;
    font-weight: bold;
    padding: 25px 32px;
    text-decoration: none;
  }
  
  ul.topnav li a:hover:not(.active) {background-color: rgb(55, 81, 165);}
  
  ul.topnav li a.active {background-color: #0cc0d8;}
  
  ul.topnav li.right {float: right;}
      
  @media screen and (max-width: 600px) {
    ul.topnav li.right, 
    ul.topnav li {float: none;}
  }

  /* Services Section on product page */
.services {
  background: rgb(10, 10, 10);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.services h1 {
  background-color: #77ff7e;
  background-image: linear-gradient(
    to right,
    #00eeff 0%,
    #0df1de 0%,
    #0ad3f7 21%,
    #2b86db 52%,
    #23a6da 78%,
    #06afda 100%
  );
  background-size: 100%;
  -webkit-background-clip: text;
  -moz-background-clip: text;
  -webkit-text-fill-color: transparent;
  -moz-text-fill-color: transparent;
  margin-bottom: 5rem;
  font-size: 2.5rem;
}

.services__container {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
}

.services__card {
  margin: 1rem;
  height: 525px;
  width: 400px;
  border-radius: 4px;
  background-image: linear-gradient(
      to bottom,
      rgba(0, 0, 0, 0) 0%,
      rgba(17, 17, 17, 0.6) 100%
    ),
    url('img/bus.PNG');
  background-size: cover;
  position: relative;
  color: #fff;
}

.services__card:before {
  opacity: 0.2;
}

.services__card:nth-child(2) {
  background-image: linear-gradient(
      to bottom,
      rgba(0, 0, 0, 0) 0%,
      rgba(17, 17, 17, 0.9) 100%
    ),
    url('img/bus.PNG');
}

.services__card h2 {
  position: absolute;
  top: 350px;
  left: 30px;
}

.services__card p {
  position: absolute;
  top: 400px;
  left: 30px;
}

.services__card button {
  color: #fff;
  padding: 10px 20px;
  border: none;
  outline: none;
  border-radius: 4px;
  background: #19b6bb;
  position: absolute;
  top: 440px;
  left: 30px;
  font-size: 1rem;
}

.services__card button:hover {
  cursor: pointer;
}

.services__card:hover {
  transform: scale(1.075);
  transition: 0.2s ease-in;
  cursor: pointer;
}

@media screen and (max-width: 960px) {
  .services {
    height: 1600px;
  }

  .services h1 {
    font-size: 2rem;
    margin-top: 12rem;
  }
}

@media screen and (max-width: 480px) {
  .services {
    height: 1400px;
  }

  .services h1 {
    font-size: 1.2rem;
  }

  .services__card {
    width: 300px;
  }
}



/* On smaller screens, decrease text size */
@media only screen and (max-width: 300px) {
  .text {font-size: 11px}
}

/* "not needed*/

 
 
 
 .textcontainer2{

  font-size: 2.5vh;
  color: whitesmoke;

  /* buttons */


}.main__btn {
  font-size: 1rem;
  background-image: linear-gradient(to top, #008cff 0%, #0e0bec 100%);
  padding: 14px 32px;
  border: none;
  border-radius: 4px;
  color: #fff;
  cursor: pointer;
  position: relative;
  transition: all 0.35s;
  outline: none;
  bottom: -400px;
  left: 50%;
  margin-left: -100px;
  top: 50%;
  margin-top: -100px;
  margin-bottom: 400px;
  
}

.main__btn a {
  position: relative;
  z-index: 2;
  color: #fff;
  text-decoration: none;
}

.main__btn:after {
  position: absolute;
  content: '';
  top: 0;
  left: 0;
  width: 0;
  height: 100%;
  background: #4837ff;
  transition: all 0.35s;
  border-radius: 4px;
}

.main__btn:hover {
  color: #fff;
}

.main__btn:hover:after {
  width: 100%;
}



  
 <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="img/icon.png">

<link rel="stylesheet" href="styles.css">

<style>


h1{
  font-size: 60px;
margin:0;
padding:0;
text-align: center;
font-family: 'Courier New', Courier, monospace;
position:absolute ;
top: 50%;
left: 50%;
bottom: -80px;
margin-top: -50;
margin-left: -100;
margin-bottom: 80px;
transform: translate(-50%);
color: blue;
}





</style>
</head>
<body>

<div class="alert">
  <span class="closebtn" onclick="this.parentElement.style.display='none';">amp;times;</span> 
  <center><strong>DEALS NOW ON!</strong> Upto 30% discounts this christmas
</div></center>

<ul class="topnav">
    
<li><img src="img/logo.png"></li>
  <li><a class="active" href="index.html">Home</a></li>
  <li><a href="Products.html">Products</a></li>
  <li><a href="#contact">Contact Us</a></li>
  <li class="right"><a href="#about">About Us</a></li>
</ul>


<h1> Kipplo.co.uk </h1>


<button class="main__btn"><a href="#">More Information</a></button>

    

</body>
</html> 

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

1. Без полной картины мы не можем диагностировать проблему. Пожалуйста, предоставьте либо весь код, либо ссылку на интерфейс.

2. Конечно, я отредактировал сообщение!

3. «Я хочу, чтобы заголовок и кнопка находились в одном и том же месте в середине страницы» — тогда вам, вероятно, следует обернуть эти два элемента в элемент контейнера, а затем расположить его вместо двух из них по отдельности.

4. Хорошая идея, я внесу изменения в свой код!

Ответ №1:

для этого вы можете использовать flex box.

1. Я заключил все элементы в div с классом в качестве контейнера и добавил следующие свойства

 .container {
    display: flex;
    flex-direction: column;
    height: 100vh;
}
 

2. обернутая кнопка и тег h1 в div с классом btn-центрирование со свойствами

 .btn-centering {
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}
 

3. завернул тег h1 в div с текстом класса и свойством

 .text {
    width: 100%;
}
 

и удалил все эти свойства положения.

 body {
    background-color: rgb(10, 10, 10);
}

html,
body {
    max-width: 100%;
    overflow-x: hidden;
}

/* Announcment bar */
.alert {
    padding: 20px;
    background-color: #2a7a85;
    color: white;
}

.closebtn {
    margin-left: 15px;
    color: white;
    font-weight: bold;
    float: right;
    font-size: 22px;
    line-height: 20px;
    cursor: pointer;
    transition: 0.3s;
}

.closebtn:hover {
    color: black;
}

body {
    margin: 0;
}
/* Navigation bar */
ul.topnav {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: rgb(248, 248, 248);
}

ul.topnav li {
    float: left;
}

ul.topnav li a {
    display: block;
    color: black;
    text-align: center;
    font-weight: bold;
    padding: 25px 32px;
    text-decoration: none;
}

ul.topnav li a:hover:not(.active) {
    background-color: rgb(55, 81, 165);
}

ul.topnav li a.active {
    background-color: #0cc0d8;
}

ul.topnav li.right {
    float: right;
}

@media screen and (max-width: 600px) {
    ul.topnav li.right,
    ul.topnav li {
        float: none;
    }
}

/* Services Section on product page */
.services {
    background: rgb(10, 10, 10);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

.services h1 {
    background-color: #77ff7e;
    background-image: linear-gradient(
        to right,
        #00eeff 0%,
        #0df1de 0%,
        #0ad3f7 21%,
        #2b86db 52%,
        #23a6da 78%,
        #06afda 100%
    );
    background-size: 100%;

    -webkit-text-fill-color: transparent;
    -moz-text-fill-color: transparent;
    margin-bottom: 5rem;
    font-size: 2.5rem;
}

.services__container {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
}

.services__card {
    margin: 1rem;
    height: 525px;
    width: 400px;
    border-radius: 4px;
    background-image: linear-gradient(
            to bottom,
            rgba(0, 0, 0, 0) 0%,
            rgba(17, 17, 17, 0.6) 100%
        ),
        url('img/bus.PNG');
    background-size: cover;
    position: relative;
    color: #fff;
}

.services__card:before {
    opacity: 0.2;
}

.services__card:nth-child(2) {
    background-image: linear-gradient(
            to bottom,
            rgba(0, 0, 0, 0) 0%,
            rgba(17, 17, 17, 0.9) 100%
        ),
        url('img/bus.PNG');
}

.services__card h2 {
    position: absolute;
    top: 350px;
    left: 30px;
}

.services__card p {
    position: absolute;
    top: 400px;
    left: 30px;
}

.services__card button {
    color: #fff;
    padding: 10px 20px;
    border: none;
    outline: none;
    border-radius: 4px;
    background: #19b6bb;
    position: absolute;
    top: 440px;
    left: 30px;
    font-size: 1rem;
}

.services__card button:hover {
    cursor: pointer;
}

.services__card:hover {
    transform: scale(1.075);
    transition: 0.2s ease-in;
    cursor: pointer;
}

@media screen and (max-width: 960px) {
    .services {
        height: 1600px;
    }

    .services h1 {
        font-size: 2rem;
        margin-top: 12rem;
    }
}

@media screen and (max-width: 480px) {
    .services {
        height: 1400px;
    }

    .services h1 {
        font-size: 1.2rem;
    }

    .services__card {
        width: 300px;
    }
}

/* On smaller screens, decrease text size */
@media only screen and (max-width: 300px) {
    .text {
        font-size: 11px;
    }
}

/* "not needed*/

.textcontainer2 {
    font-size: 2.5vh;
    color: whitesmoke;

    /* buttons */
}
.main__btn {
    font-size: 1rem;
    background-image: linear-gradient(to top, #008cff 0%, #0e0bec 100%);
    padding: 14px 32px;
    border: none;
    border-radius: 4px;
    color: #fff;
    cursor: pointer;
    transition: all 0.35s;
    outline: none;
}

.main__btn a {
    position: relative;
    z-index: 2;
    color: #fff;
    text-decoration: none;
}

.main__btn:after {
    position: absolute;
    content: '';
    top: 0;
    left: 0;
    width: 0;
    height: 100%;
    background: #4837ff;
    transition: all 0.35s;
    border-radius: 4px;
}

.main__btn:hover {
    color: #fff;
}

.main__btn:hover:after {
    width: 100%;
}

h1 {
    font-size: 60px;
    margin: 0;
    padding: 0;
    font-family: 'Courier New', Courier, monospace;
    color: blue;
    word-wrap: break-word;
    text-align: center;
}

.container {
    display: flex;
    flex-direction: column;
    height: 100vh;
}

.btn-centering {
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.text {
    width: 100%;
} 
 <!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="icon" href="img/icon.png" />

        <link rel="stylesheet" href="stack_overflow1.css" />
    </head>
    <body>
        <div class="container">
            <div class="alert">
                <span
                    class="closebtn"
                    onclick="this.parentElement.style.display='none';"
                    >amp;times;</span
                >
                <center>
                    <strong>DEALS NOW ON!</strong> Upto 30% discounts this
                    christmas
                </center>
            </div>

            <ul class="topnav">
                <li><img src="img/logo.png" /></li>
                <li><a class="active" href="index.html">Home</a></li>
                <li><a href="Products.html">Products</a></li>
                <li><a href="#contact">Contact Us</a></li>
                <li class="right"><a href="#about">About Us</a></li>
            </ul>

            <div class="btn-centering">
                <div class="text"><h1>Kipplo.co.uk</h1></div>
                <button class="main__btn">
                    <a href="#">More Information</a>
                </button>
            </div>
        </div>
    </body>
</html> 

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

1. Этот код идеален, сможете ли вы поместить kipplo.co.uk и кнопка в середине страницы вместо верхнего центра? с уважением, Вали.

2. пожалуйста, проверьте. Я обновил код @Validix

3. Именно так мне бы и хотелось @runtimeerror, мне просто нужно выяснить, почему он увеличивается при наведении на него курсора, который, я полагаю, является классом наведения? Большое вам спасибо!

4. да, я только что увидел, что просто удалите этот класс .main__btn:hover:after { width: 100%; }

5. Готово, большое спасибо за ваше время. единственное, что мне нужно разобраться, это функция наведения / опрокидывания, чтобы она продолжала работать по назначению. Я действительно ценю это!

Ответ №2:

Вы можете использовать

 @media only screen and (min-height: 700px;) {
    h1 {
       bottom:10%;
    }
}
 

Это позволяет выбрать h1 в запросе @media высотой менее 600 пикселей и сделать h1 10% снизу, подробнее о медиа-запросах читайте здесь; https://www.w3schools.com/cssref/css3_pr_mediaquery.asp

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

1. Я попытался использовать медиа-библиотеку, и в настоящее время она делает то же самое, что и предыдущая попытка, я также следовал структуре кода школ w3, на которые вы также ссылались, я не уверен, что использую код правильно. Спасибо, Вали.