¿Cómo ajustar dinámicamente el ancho del contenedor de texto según el tamaño de la pantalla usando CSS?

En este artículo, le hemos dado un párrafo de texto y la tarea es ajustar el ancho del texto dinámicamente según el tamaño de la pantalla usando HTML y CSS. Algunas de las propiedades importantes utilizadas en el código son las siguientes:

  • display-grid: Nos ayuda a mostrar el contenido de la página en la estructura de cuadrícula.
  • grid-gap: esta propiedad establece la cantidad mínima de espacio entre dos cuadrículas.
  • ajuste automático: toma las restricciones requeridas y ajusta el contenido de acuerdo con el tamaño de la pantalla.
  • <div>: es la etiqueta de división y nos ayuda a definir una sección particular del código HTML para que pueda consultarse y editarse fácilmente más adelante en la hoja de estilo CSS.
  • auto-fit: Hace que todas las columnas disponibles en la pantalla encajen en el espacio disponible y las expande según sea necesario para ocupar las filas.
  • Función min() y max(): Esta función está muy relacionada con la función matemática que define un rango particular de la función, es decir, mayor o igual a min y menor o igual a max.
  • @media(min-width): es una propiedad de CSS en la que la condición de esta etiqueta solo se aplica cuando el ancho mínimo de la pantalla alcanza los 950 px.

Ejemplo 1: Es un ejemplo sencillo. Aquí, usaremos la etiqueta <div> para especificar cada cita por separado y repetir la función en la parte CSS.

HTML

<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
  
    <style>
        body {
            margin: 0;
            font-family: 'Nunito';
        }
          
        .top {
            padding: 3em;
            display: grid;
            grid-gap: 3em;
            grid-template-columns: repeat(4, 250px);
            .quote {
                padding: 3em;
                border-radius: .3em;
                box-shadow: 10px 10px 30px rgba(0, 0, 0, 0.1);
                p {
                    margin-top: 0;
                }
                span {
                    font-weight: bold;
                    position: relative;
                    margin-left: 20px;
                    &:before {
                        content: '';
                        position: absolute;
                        height: 1px;
                        width: 20px;
                        border-bottom: 1px solid black;
                        top: 20px;
                    }
                }
            }
        }
          
        @media(min-width:950px) {
            .top {
                grid-template-columns: repeat(4, 1fr);
            }
        }
    </style>
  
</head>
  
<body>
    <div class="top">
        <div class="quote">
  
            <p>
                With the idea of imparting programming 
                knowledge, Mr. Sandeep Jain, an IIT 
                Roorkee alumnus started a dream, 
                GeeksforGeeks. Whether programming 
                excites you or you feel stifled, wondering
                how to prepare for interview questions or
                how to ace data structures and algorithms,
                GeeksforGeeks is a one-stop solution. With 
                every tick of time, we are adding arrows
                in our quiver. From articles on various 
                computer science subjects to programming 
                problems for practice, from basic to 
                premium courses, from technologies to 
                entrance examinations, we have been 
                building ample content with superior quality.
            </p>
            <br>
            <span>GFG</span>
        </div>
        <div class="quote span-2">
  
            <p>
                With the idea of imparting programming 
                knowledge, Mr. Sandeep Jain, an IIT 
                Roorkee alumnus started a dream, 
                GeeksforGeeks. Whether programming 
                excites you or you feel stifled, wondering
                how to prepare for interview questions or
                how to ace data structures and algorithms,
                GeeksforGeeks is a one-stop solution. With 
                every tick of time, we are adding arrows
                in our quiver. From articles on various 
                computer science subjects to programming 
                problems for practice, from basic to 
                premium courses, from technologies to 
                entrance examinations, we have been 
                building ample content with superior quality.
            </p>
            <br>
            <span>GFG</span>
        </div>
  
        <div class="quote">
            <p>
                With the idea of imparting programming 
                knowledge, Mr. Sandeep Jain, an IIT 
                Roorkee alumnus started a dream, 
                GeeksforGeeks. Whether programming 
                excites you or you feel stifled, wondering
                how to prepare for interview questions or
                how to ace data structures and algorithms,
                GeeksforGeeks is a one-stop solution. With 
                every tick of time, we are adding arrows
                in our quiver. From articles on various 
                computer science subjects to programming 
                problems for practice, from basic to 
                premium courses, from technologies to 
                entrance examinations, we have been 
                building ample content with superior quality.
            </p>
            <span>GFG</span>
        </div>
  
        <div class="quote">
            <p>
                With the idea of imparting programming 
                knowledge, Mr. Sandeep Jain, an IIT 
                Roorkee alumnus started a dream, 
                GeeksforGeeks. Whether programming 
                excites you or you feel stifled, wondering
                how to prepare for interview questions or
                how to ace data structures and algorithms,
                GeeksforGeeks is a one-stop solution. With 
                every tick of time, we are adding arrows
                in our quiver. From articles on various 
                computer science subjects to programming 
                problems for practice, from basic to 
                premium courses, from technologies to 
                entrance examinations, we have been 
                building ample content with superior quality.
            </p>
            <span>GFG</span>
        </div>
    </div>
</body>
  
</html>

Producción:

Al minimizar la pantalla de salida, no podemos ver la mitad del texto de la segunda fila y aparece una barra de desplazamiento en la parte inferior de la ventana para desplazarse. Esto no se ve bien y puede causar problemas si el usuario está viendo el sitio web en su teléfono móvil.

Ejemplo 2: este es un mejor enfoque, ya que nos brinda una salida más organizada y sin problemas con la adición de solo una propiedad conocida como ajuste automático. 

HTML

<!DOCTYPE html>
<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
      
    <style>
        body {
            margin: 0;
            font-family: 'Nunito';
        }
          
        .top {
            padding: 3em;
            display: grid;
            grid-gap: 2em;
            grid-template-columns: repeat(
                    auto-fit, minmax(250px, 1fr));
  
            .quote {
                padding: 2em;
                border-radius: .3em;
                box-shadow: 10px 10px 30px 
                        rgba(0, 0, 0, 0.1);
                p {
                    margin-top: 0;
                }
                span {
                    font-weight: bold;
                    position: relative;
                    margin-left: 15px;
                    &:before {
                        content: '';
                        position: absolute;
                        height: 1px;
                        width: 10px;
                        border-bottom: 1px solid black;
                        top: 10px;
                        left: -15px;
                    }
                }
            }
        }
    </style>
</head>
  
<body>
    <div class="top">
        <div class="quote">
            <p>
                With the idea of imparting programming 
                knowledge, Mr. Sandeep Jain, an IIT 
                Roorkee alumnus started a dream, 
                GeeksforGeeks. Whether programming 
                excites you or you feel stifled, wondering
                how to prepare for interview questions or
                how to ace data structures and algorithms,
                GeeksforGeeks is a one-stop solution. With 
                every tick of time, we are adding arrows
                in our quiver. From articles on various 
                computer science subjects to programming 
                problems for practice, from basic to 
                premium courses, from technologies to 
                entrance examinations, we have been 
                building ample content with superior quality.
            </p>
            <br>
            <span>GFG</span>
        </div>
  
        <div class="quote span-2">
            <p>
                With the idea of imparting programming 
                knowledge, Mr. Sandeep Jain, an IIT 
                Roorkee alumnus started a dream, 
                GeeksforGeeks. Whether programming 
                excites you or you feel stifled, wondering
                how to prepare for interview questions or
                how to ace data structures and algorithms,
                GeeksforGeeks is a one-stop solution. With 
                every tick of time, we are adding arrows
                in our quiver. From articles on various 
                computer science subjects to programming 
                problems for practice, from basic to 
                premium courses, from technologies to 
                entrance examinations, we have been 
                building ample content with superior quality.
            </p>
            <br>
            <span>GFG</span>
        </div>
  
        <div class="quote">
            <p>
                With the idea of imparting programming 
                knowledge, Mr. Sandeep Jain, an IIT 
                Roorkee alumnus started a dream, 
                GeeksforGeeks. Whether programming 
                excites you or you feel stifled, wondering
                how to prepare for interview questions or
                how to ace data structures and algorithms,
                GeeksforGeeks is a one-stop solution. With 
                every tick of time, we are adding arrows
                in our quiver. From articles on various 
                computer science subjects to programming 
                problems for practice, from basic to 
                premium courses, from technologies to 
                entrance examinations, we have been 
                building ample content with superior quality.
            </p>
            <span>GFG</span>
        </div>
  
        <div class="quote">
            <p>
                With the idea of imparting programming 
                knowledge, Mr. Sandeep Jain, an IIT 
                Roorkee alumnus started a dream, 
                GeeksforGeeks. Whether programming 
                excites you or you feel stifled, wondering
                how to prepare for interview questions or
                how to ace data structures and algorithms,
                GeeksforGeeks is a one-stop solution. With 
                every tick of time, we are adding arrows
                in our quiver. From articles on various 
                computer science subjects to programming 
                problems for practice, from basic to 
                premium courses, from technologies to 
                entrance examinations, we have been 
                building ample content with superior quality.
            </p>
            <span>GFG</span>
        </div>
    </div>
  
</body>
  
</html>

Producción: 

En este método podemos ver que al minimizar la pantalla todas las filas se ajustan como columnas una debajo de la otra. Y se nos da una barra de desplazamiento vertical para la última cita. Aquí no se omite texto de una línea y podemos leer la cita completa.

Publicación traducida automáticamente

Artículo escrito por debanshupanda2001 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *