Я пытаюсь понять, как сделать первое появление на экране в полноэкранном режиме. Вся страница будет полноэкранной, и когда кто-то прокручивает страницу вниз, она переходит на новый экран. Я не могу точно понять, как это сделать.
body {
margin: 0 0 0 0;
}
#sample_img_1 {
height: 900px;
width: absolute;
background-image: linear-gradient(to right, green, blue);
}
#sample_img_2 {
height: 200px;
width: absolute;
background-image: linear-gradient(to right, red, orange);
}
<p id = "sample_img_1"></p>
<p id = "sample_img_2"></p>
Я поставил это там, чтобы изображения были на всю ширину экрана.
Как бы мне не хотелось это говорить, я особо не изучал «ширину» в CSS.
Это совсем не проблема; мы все должны с чего-то начинать. Мое предложение всегда будет заключаться в том, что если CSS (или JS, или HTML...) не работает так, как вы ожидаете, всегда стоит поискать документацию, и, как указано выше, я всегда буду предлагать MDN в качестве первого средства для работы в Интернете. разработки (хотя библиотеки и фреймворки также имеют свою собственную документацию, которую стоит проверить).
MDN звучит как интересный язык. Я буду смотреть в него!
Вы можете изучить использование единиц CSS vw и vh. Они обозначают ширину области просмотра и высоту области просмотра. Я использовал их в некоторых случаях, когда мне нужно, чтобы размер элемента соответствовал размеру экрана устройства. Например:
.full-width {
width: 100vw;
height: 100vh;
position: absolute;
top: 0;
left: 0;
background-color: pink;
}
Edit: вот ссылка чтобы узнать больше о W3schools
Эта информация была не совсем тем, что я искал, но она очень полезна для других вещей, над которыми я работал. Спасибо!
Сделать высоту каждой секции 100вх;
body {
margin: 0;
}
#sample_img_1 {
height: 100vh;
width: 100%;
background-image: linear-gradient(to right, green, blue);
}
#sample_img_2 {
height: 100vh;
width: 100%;
background-image: linear-gradient(to right, red, orange);
}
А затем следуйте этому потоку stackoverflow;
При прокрутке вниз прокрутите 100vh вниз
Во-первых, проблемы с вашим существующим кодом:
body {
/* this is absolutely fine: */
margin: 0 0 0 0;
/* but could easily be replaced by the more concise:
margin: 0;
*/
}
#sample_img_1 {
height: 900px;
/* this is a valid property ("width") with an invalid property-value,
"absolute" is valid only for the "position" property; the "width"
property requires a valid CSS length: */
width: absolute;
background-image: linear-gradient(to right, green, blue);
}
#sample_img_2 {
height: 200px;
/* as above, this is an invalid property-value: */
width: absolute;
background-image: linear-gradient(to right, red, orange);
}
/* as mentioned in the HTML, this rule could have reduced repetition:
p {
height: 200px;
width: 500px; (or any other valid value)
}
*/
<!-- while the HTML is perfectly valid, it seems sensible to point out
that identifying all elements with an "id" attribute is rarely
necessary, but that rarity depends on your understanding of CSS
and the requirements of your use-case; but in this case you could
have simplified your CSS, and minified repetition, by declaring
width and height rules on a style rule applied to all <p> elements:-->
<p id = "sample_img_1"></p>
<p id = "sample_img_2"></p>
Чтобы исправить вышесказанное, чтобы фоновые изображения элементов <p> занимали всю ширину страницы:
body {
/* here I've specified zero padding and zero margin: */
padding: 0;
margin: 0;
}
p {
/* removed the default margin from the <p> elements: */
margin: 0;
width: 100%;
}
#sample_img_1 {
/* I left the "height" as you defined them, but I'm not sure
why they have these heights: */
height: 900px;
background-image: linear-gradient(to right, green, blue);
}
#sample_img_2 {
height: 200px;
background-image: linear-gradient(to right, red, orange);
}
<p id = "sample_img_1"></p>
<p id = "sample_img_2"></p>
Хотя вместо вышеизложенного я бы предложил следующий подход с пояснительными комментариями в коде:
/* a simple reset to all elements, as well as the
::before and ::after pseudo-elements: */
*,
::before,
::after {
/* forcing the browser to calculate element-sizes
including their assigned padding and borders: */
box-sizing: border-box;
/* removing default margin and padding: */
margin: 0;
padding: 0;
}
html,
body {
/* both of the following are to have the <html> and <body>
elements take up the full size available to them;
block-size, a CSS logical property equivalent to the
axis on which element blocks are laid out (vertical,
in English and languages derived from Latin): */
block-size: 100%;
/* inline-size, a CSS logical property equivalent to the
axis on which inline content is laid out (horizontal,
in English and languages derived from Latin): */
inline-size: 100%;
/* here we enforce scroll-snapping on the y axis: */
scroll-snap-type: y mandatory;
}
body {
/* defining a CSS counter that is reset by the <body>: */
counter-reset: sectionCount;
}
section {
/* defining the background-image of the <section> elements, using
the var() function along with two CSS custom properties: */
background-image: linear-gradient(to right, var(--gradientColor1), var(--gradientColor2));
/* here we use display: grid purely to take advantage of the
following 'place-content' rule to center the pseudo-element
within its parent: */
display: grid;
place-content: center;
/* using logical properties to set the size of the element(s) on the
block and inline axes, using viewport-height (vh) and viewport-width
(vw) units to have them take the full height and width of the viewport: */
block-size: 100vh;
inline-size: 100vw;
/* defining the snapping point of the element: */
scroll-snap-align: start;
}
/* this is irrelevent to the demo, but is used to number the <section>
elements: */
section::before {
/* defining a border in the current-color: */
border: 3px solid currentColor;
color: #fff;
/* incrementing the named CSS counter: */
counter-increment: sectionCount;
/* setting the content of the pseudo-element, using the CSS counter()
function, formatting that counter with decimal-leading-zero: */
content: counter(sectionCount, decimal-leading-zero);
font-size: 6em;
padding: 1em;
}
/* defining the CSS custom properties that are applied in the
background-image property: */
.page:nth-child(odd) {
--gradientColor1: green;
--gradientColor2: blue;
}
.page:nth-child(even) {
--gradientColor1: red;
--gradientColor2: orange;
}
<!-- I've changed your posted CSS, and removed the 'id' properties
entirely; this is to allow easier addition/removal of content;
the choice to switch to <section> instead of <p> was made to
more logically/semantically group associated content; but the
elements are largely irrelevant and require only that the
CSS for sizing (and scrolling if required) is applied to the
elements you prefer to use: -->
<section class = "page"></section>
<section class = "page"></section>
<section class = "page"></section>
<section class = "page"></section>
<section class = "page"></section>
<section class = "page"></section>
<section class = "page"></section>
<section class = "page"></section>
<section class = "page"></section>
<section class = "page"></section>
Демонстрация JS Fiddle.
Использованная литература:
Библиография:
Чего вы ожидаете от width: absolute; достижения? Пробовали ли вы просматривать ресурсы и документацию в Интернете? Как, например, MDN , как так: ширина.